Copy Excel Worksheets with JavaScript in React

Copying worksheets is one of the most common and efficient operations in everyday Excel document processing — whether you are quickly creating similar reports from a template or consolidating data across multiple documents. Spire.XLS for JavaScript handles this entirely in the browser via WebAssembly, using a virtual file system (VFS) to manage input and output files — no backend server required.

This article covers three core features:

For installation and project setup, refer to Integrating Spire.XLS for JavaScript in a React Project. The examples below assume Spire.XLS is installed and the WebAssembly module is initialized.


Copy a Worksheet Within the Same Workbook

Duplicating a worksheet within the same workbook is a frequent development task — for example, quickly creating next month's report copy from a monthly template. Spire.XLS for JavaScript provides the CopyFrom method to duplicate a worksheet. The copied sheet retains all content from the source worksheet, including data, styles, fonts, colors, borders, column widths, and row heights.

function App() {
  const sheetToSVG = async () => {
    // Get the Spire.XLS WASM module
    const xlsModule = window.wasmModule?.spirexls;

    // Check if the module is ready
    if (!xlsModule) {
      alert('Spire.Xls is not ready yet');
      return;
    }

    // Load fonts and the Excel file into VFS
    await window.spire.FetchFileToVFS('ARIAL.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);
    const inputFileName = 'Sample.xlsx';
    await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}data/`);

    // Load the workbook
    const workbook = new xlsModule.Workbook();
    workbook.LoadFromFile({ fileName: inputFileName });

    // Get the first worksheet
    let sheet = workbook.Worksheets.get(0);

    // Add a new worksheet
    let sheet1 = workbook.Worksheets.Add("MySheet");

    // Copy the first worksheet into the newly added sheet
    sheet1.CopyFrom(sheet);

    const outputFileName = "CopySheetWithinWorkbook_output.xlsx";
    workbook.SaveToFile({ fileName: outputFileName });

    // Release the workbook object to free resources
    workbook.Dispose();

    // Read the converted file from VFS and trigger download
    const fileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
    const blob = new Blob([fileArray], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = outputFileName;
    a.click();
    URL.revokeObjectURL(url);
  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Copy Worksheet Within Workbook</h1>
      <button onClick={sheetToSVG}>
        Start
      </button>
    </div>
  );
}

export default App;

When using CopyFrom, data, styles, fonts, colors, borders, and column widths from the source worksheet are fully preserved in the new sheet.

Copying a worksheet within the same workbook


Copy a Worksheet Across Workbooks

In real-world scenarios, data from multiple Excel files often needs to be consolidated into a single workbook — for example, extracting specific sheets from departmental reports and merging them into a master sheet. The AddCopy method lets you copy a worksheet from the source workbook into the target workbook with all its content intact.

function App() {
  const sheetToSVG = async () => {
    // Get the Spire.XLS WASM module
    const xlsModule = window.wasmModule?.spirexls;

    // Check if the module is ready
    if (!xlsModule) {
      alert('Spire.Xls is not ready yet');
      return;
    }

    // Load fonts and the Excel files into VFS
    await window.spire.FetchFileToVFS('arial.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);
    const sourceFileName = 'ReadImages.xlsx';
    const targetFileName = 'Sample.xlsx';
    await window.spire.FetchFileToVFS(sourceFileName, '', `${process.env.PUBLIC_URL}data/`);
    await window.spire.FetchFileToVFS(targetFileName, '', `${process.env.PUBLIC_URL}data/`);

    // Load the source workbook
    const sourceWorkbook = new xlsModule.Workbook();
    sourceWorkbook.LoadFromFile({ fileName: sourceFileName });

    // Get the first worksheet of the source workbook
    const srcWorksheet = sourceWorkbook.Worksheets.get(0);

    // Load the target workbook
    const targetWorkbook = new xlsModule.Workbook();
    targetWorkbook.LoadFromFile({ fileName: targetFileName });

    // Add a new worksheet in the target workbook and copy the source sheet into it
    targetWorkbook.Worksheets.AddCopy({ sheet: srcWorksheet });

    // Save the target workbook
    const outputFileName = "CopyAcrossWorkbooks_output.xlsx";
    targetWorkbook.SaveToFile({ fileName: outputFileName });

    // Release resources
    sourceWorkbook.Dispose();
    targetWorkbook.Dispose();

    // Read the converted file from VFS and trigger download
    const fileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
    const blob = new Blob([fileArray], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = outputFileName;
    a.click();
    URL.revokeObjectURL(url);
  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Copy Worksheet Across Workbooks</h1>
      <button onClick={sheetToSVG}>
        Start
      </button>
    </div>
  );
}

export default App;

When copying across workbooks, all data and styles from the source worksheet are preserved — AddCopy copies the complete worksheet content into the target workbook.

Copying a worksheet across workbooks


Copy a Selected Cell Range

Sometimes you do not need to copy an entire worksheet — you only need to copy a specific cell range (such as a particular data table or summary result) to a target location. Spire.XLS for JavaScript provides the Copy method, which copies data, styles, and formatting from the source range to the starting position of the target range.

function App() {
  const sheetToSVG = async () => {
    // Get the Spire.XLS WASM module
    const xlsModule = window.wasmModule?.spirexls;

    // Check if the module is ready
    if (!xlsModule) {
      alert('Spire.Xls is not ready yet');
      return;
    }

    // Load the source Excel file into VFS
    await window.spire.FetchFileToVFS('ARIAL.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);
    const inputFileName = 'Sample.xlsx';
    await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}data/`);

    // Load the workbook
    const workbook = new xlsModule.Workbook();
    workbook.LoadFromFile({ fileName: inputFileName });

    // Get the first row of the first worksheet as the source range
    const sheet = workbook.Worksheets.get(0);
    const sourceRange = sheet.Range.get("A1:E1");

    // Add a new worksheet
    let sheet1 = workbook.Worksheets.Add("AddSheet");

    // Copy the source range to the starting position of the target worksheet
    sheet.Copy(sourceRange, sheet1, sheet.FirstRow, sheet.FirstColumn, true);

    // Save the workbook
    const outputFileName = "CopyRange_output22.xlsx";
    workbook.SaveToFile({ fileName: outputFileName });

    // Release resources
    workbook.Dispose();

    // Read the converted file from VFS and trigger download
    const fileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
    const blob = new Blob([fileArray], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = outputFileName;
    a.click();
    URL.revokeObjectURL(url);
  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Copy Range</h1>
      <button onClick={sheetToSVG}>
        Start
      </button>
    </div>
  );
}

export default App;

The Copy method transfers data, styles, and formatting from the source range to the target range — ideal for lightweight scenarios where only partial data extraction is needed.

Copying a selected cell range


FAQ

Column width differs after copying

Cause: Font mismatch between the source and target workbooks.

Solution: Ensure all required font files are loaded into the VFS environment of the target workbook before copying across workbooks:

await window.spire.FetchFileToVFS(
  'arial.ttf', '/Library/Fonts/', '/'
);

Range content is pasted at the wrong position

Cause: Incorrect destRow and destColumn parameters in the Copy method, causing data to be pasted at an unexpected location.

Solution: Confirm that the destination row and column indices start from 1 (not 0), and verify the row and column range of the target worksheet before copying.


Get a Free License

Spire.XLS for JavaScript offers a 30-day full-featured free trial license with no functional limitations. Apply here to evaluate before purchasing.