Ritsaert Hornstra
Ritsaert Hornstra

Reputation: 5111

Copy a range of cells or worksheet from using ExcelJS

Is it possible / is there a convenience function to copy a range of cells and/or a whole worksheet from one Excel sheet to another using ExcelJS?

Upvotes: 1

Views: 10440

Answers (3)

Yunus Kerem Türk
Yunus Kerem Türk

Reputation: 21

var sourceWorkbook= new Excel.Workbook();
var sourceWorksheet;
sourceWorkbook.xlsx.readFile("template.xlsx").then(function(){
    sourceWorksheet= sourceWorkbook.getWorksheet(1);
    var targetWorkbook = new Excel.Workbook;
    var targetSheet = targetWorkbook.addWorksheet();
    sourceWorksheet.eachRow((row, rowNumber) => {
        var newRow = targetSheet.getRow(rowNumber);
        row.eachCell((cell, colNumber) => {
            var newCell = newRow.getCell(colNumber)
            for(var prop in cell)
            {
                newCell[prop] = cell[prop];
            }
        })
   })  

This is what I done with my project. It works well.

Upvotes: 2

Tính Ngô Quang
Tính Ngô Quang

Reputation: 4652

copying worksheets with Merged cells

 var ws1 = workbook.getWorksheet('demo');
  let copySheet = workbook.addWorksheet('newdemo');

  copySheet.model = Object.assign(ws1.model, {
    mergeCells: ws1.model.merges
  });
  copySheet.name = 'new demo';

Upvotes: 5

tejp124
tejp124

Reputation: 376

You can copy the whole worksheet from one Excel sheet to another using ExcelJS. Below code will work

const Excel = require('exceljs');

async function copyExcel() {
    let targetWorkbook = new Excel.Workbook();
    targetWorkbook = await targetWorkbook.xlsx.readFile('target.xlsx');
    const targetWorksheet = targetWorkbook.getWorksheet('target'); // you can add new sheet as well.

    let sourceWorkbook = new Excel.Workbook();
    sourceWorkbook = await sourceWorkbook.xlsx.readFile('source.xlsx');
    const sourceWorksheet = sourceWorkbook.getWorksheet('source');

    sourceWorksheet.eachRow({ includeEmpty: false }, (row, rowNumber) => {
        var targetRow = targetWorksheet.getRow(rowNumber);
        row.eachCell({ includeEmpty: false }, (cell, cellNumber) => {
            targetRow.getCell(cellNumber).value = cell.value;
        });
        row.commit();
    });
    await targetWorkbook.xlsx.writeFile('target.xlsx');
}

copyExcel();

Upvotes: 0

Related Questions