Copy Excel Rows, Columns, and Cells with Formatting in React

Copying data within Excel files while preserving formatting is a common requirement in web-based spreadsheet applications. Spire.XLS for JavaScript runs entirely in the browser via WebAssembly, using a virtual file system (VFS) to manage input and output files — no backend server required. It provides comprehensive APIs to copy rows, columns, and cell ranges while keeping the original styles, fonts, colors, and other formatting intact.

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 Rows in Excel

With Spire.XLS for JavaScript, you can copy rows within the same worksheet or across different worksheets while preserving all formatting, formulas, and styles. This is useful when you need to duplicate structured data such as headers, summary rows, or formatted templates. Through the CopyRangeOptions parameter, you can flexibly configure copy options such as copying all formats, conditional formatting, data validation, or only formula result values. The steps are as follows:

  1. Create a Workbook object and load an existing Excel file.
  2. Get the source and destination worksheets via workbook.Worksheets.get().
  3. Get the row to copy via sheet.Rows[index].
  4. Use sheet.Copy() with the source row, destination worksheet, destination row index, and CopyRangeOptions.All to copy the row and its formatting.
  5. Copy the column widths from the source row cells to the corresponding destination row cells.
  6. Save the workbook to an Excel file using SaveToFile().

Below is a complete code example demonstrating how to copy rows in React:

function App() {
  const copyRows = 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;
    }

    // Fetch the Excel file and add it to the Virtual File System (VFS)
    let excelFileName = 'Copying.xls';
    await window.spire.FetchFileToVFS(excelFileName, '', `${process.env.PUBLIC_URL}data/`);

    // Create a new workbook and load an existing file
    const workbook = new xlsModule.Workbook();
    workbook.LoadFromFile({ fileName: excelFileName });

    // Get the source and destination worksheets
    let sheet1 = workbook.Worksheets.get(0);
    let sheet2 = workbook.Worksheets.get(1);

    // Get the row to copy
    let row = sheet1.Rows[0];

    // Copy the row to the destination worksheet with all formatting
    sheet1.Copy({ sourceRange: row, destRange: sheet2.Rows[0], copyOptions: xlsModule.CopyRangeOptions.All });

    // Copy the column widths from source row to destination row
    let columns = sheet1.Columns.length;
    for (let i = 0; i < columns; i++) {
      let columnWidth = row.Columns[i].ColumnWidth;
      sheet2.Rows[0].Columns[i].ColumnWidth = columnWidth;
    }

    // Save the workbook
    const outputFileName = 'CopyRows_out.xlsx';
    workbook.SaveToFile({ fileName: outputFileName, version: xlsModule.ExcelVersion.Version2010 });
    workbook.Dispose();

    // Read the 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 Excel Rows</h1>
      <button onClick={copyRows}>
        Generate
      </button>
    </div>
  );
}

export default App;

Row copy result

Row copy result


Copy Columns in Excel

Copying columns is equally straightforward with Spire.XLS for JavaScript. You can duplicate a column within the same worksheet or copy it to another sheet, and all cell styles, number formats, and data will be preserved. Through the CopyRangeOptions parameter, you can flexibly configure which elements to copy. This is particularly helpful for reorganizing spreadsheet layouts or replicating data structures. The steps are as follows:

  1. Create a Workbook object and load an existing Excel file.
  2. Get the source and destination worksheets.
  3. Get the column to copy via sheet.Columns[index].
  4. Use sheet.Copy() with the source column, destination worksheet, destination column index, and CopyRangeOptions.All to copy the column and its formatting.
  5. Copy the column widths and row heights from the source column cells to the corresponding destination column cells.
  6. Save the workbook to an Excel file using SaveToFile().

Below is a complete code example demonstrating how to copy columns in React:

function App() {
  const copyColumns = 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;
    }

    // Fetch the Excel file and add it to the Virtual File System (VFS)
    let excelFileName = 'Copying.xls';
    await window.spire.FetchFileToVFS(excelFileName, '', `${process.env.PUBLIC_URL}data/`);

    // Create a new workbook and load an existing file
    const workbook = new xlsModule.Workbook();
    workbook.LoadFromFile({ fileName: excelFileName });

    // Get the source and destination worksheets
    let sheet1 = workbook.Worksheets.get(0);
    let sheet2 = workbook.Worksheets.get(1);

    // Get the column to copy
    let column = sheet1.Columns[0];

    // Copy the column to the destination worksheet with all formatting
    sheet1.Copy({ sourceRange: column, destRange: sheet2.Columns[0], copyOptions: xlsModule.CopyRangeOptions.All });

    // Copy the column width and row heights from source column to destination column
    sheet2.Columns[0].ColumnWidth = column.ColumnWidth;
    let rows = column.Rows.length;
    for (let i = 0; i < rows; i++) {
      let rowHeight = column.Rows[i].RowHeight;
      sheet2.Columns[0].Rows[i].RowHeight = rowHeight;
    }

    // Save the workbook
    const outputFileName = 'CopyColumns_out.xlsx';
    workbook.SaveToFile({ fileName: outputFileName, version: xlsModule.ExcelVersion.Version2010 });
    workbook.Dispose();

    // Read the 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 Excel Columns</h1>
      <button onClick={copyColumns}>
        Generate
      </button>
    </div>
  );
}

export default App;

Column copy result

Column copy result


Copy Cells in Excel

Beyond copying entire rows and columns, Spire.XLS for JavaScript also allows you to copy specific cell ranges from one location to another while preserving all formatting. The CellRange.Copy() method provides this capability with flexible options. This gives you fine-grained control over which cells to duplicate. You can copy a range of cells within the same worksheet or to a different worksheet. The steps are as follows:

  1. Create a Workbook object and load an existing Excel file.
  2. Get the source and destination worksheets.
  3. Get the source cell range and destination cell range via sheet.Range.get().
  4. Use sourceRange.Copy() with the destination range and CopyRangeOptions.All to copy the cell range with all formatting.
  5. Copy the column widths and row heights from the source range to the destination range.
  6. Save the workbook to an Excel file using SaveToFile().

Below is a complete code example demonstrating how to copy cells in React:

function App() {
  const copyCells = 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;
    }

    // Fetch the Excel file and add it to the Virtual File System (VFS)
    let excelFileName = 'Copying.xls';
    await window.spire.FetchFileToVFS(excelFileName, '', `${process.env.PUBLIC_URL}data/`);

    // Create a new workbook and load an existing file
    const workbook = new xlsModule.Workbook();
    workbook.LoadFromFile({ fileName: excelFileName });

    // Get the source and destination worksheets
    let sheet1 = workbook.Worksheets.get(0);
    let sheet2 = workbook.Worksheets.get(1);

    // Get the source cell range and destination cell range
    let range1 = sheet1.Range.get("A1:E7");
    let range2 = sheet2.Range.get("A1:E7");

    // Copy the source range to the destination range with all formatting
    range1.Copy({ destRange: range2, copyOptions: xlsModule.CopyRangeOptions.All });

    // Copy the row heights and column widths from source to destination
    for (let i = 0; i < range1.Rows.length; i++) {
      let row = range1.Rows[i];
      for (let j = 0; j < row.Columns.length; j++) {
        let column = row.Columns[j];
        range2.Rows[i].Columns[j].ColumnWidth = column.ColumnWidth;
        range2.Rows[i].RowHeight = row.RowHeight;
      }
    }

    // Save the workbook
    const outputFileName = 'CopyCells.xlsx';
    workbook.SaveToFile({ fileName: outputFileName, version: xlsModule.ExcelVersion.Version2010 });
    workbook.Dispose();

    // Read the 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 Excel Cells</h1>
      <button onClick={copyCells}>
        Generate
      </button>
    </div>
  );
}

export default App;

Cell copy result

Cell copy result


FAQ

What happens if the target location already contains data

Cause: By default, the Copy() method overwrites existing data at the target location without merging or preserving the original content.

Solution: Choose an empty area as the destination range, or check whether the target range is empty before performing the copy. You can also back up the target data first, then execute the copy operation.

Can I copy only values without formulas

Cause: CopyRangeOptions.All copies formulas themselves, but sometimes you only need the calculated result values without preserving the formula logic.

Solution: Use the CopyRangeOptions.OnlyCopyFormulaValue option to copy only the calculated result values, not the formulas themselves:

sourceRange.Copy({ destRange: destRange, copyOptions: xlsModule.CopyRangeOptions.OnlyCopyFormulaValue });

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.