How to save a worksheet from excel as a new excel file using javascript

Viewed 736

An excel file with two worksheets in it(TAB1, TAB2).

enter image description here

How to save 'TAB1' from the below excel as a new Excel file say tab1.xlsx?

I am trying to work it out with exceljs but not sure how to save it as new file. If it cannot be done with help of exceljs please suggest any other way to get this done.

const ExcelJS = require('exceljs');

const wb = new ExcelJS.Workbook();
//const newwork =  new ExcelJS.Workbook();

filename = "abc.xlsx";
const fl = async () => {
    wb.xlsx.readFile(filename)
        .then(async function () {
            wb.eachSheet(async function (worksheet, sheetId) {
                console.log("worksheet", worksheet, "sheetid", sheetId);
                if(worksheet.name.toLocaleLowerCase() ==='tab1'){
                    var data = wb.getWorksheet(worksheet.name);
                  
                    // how to save worksheet as tab1.xlsx
                    // let dt =await newwork.xlsx.writeFile('tab1.xlsx',data);
                   
                }
            });
        });
}

fl();
2 Answers

I have created a not so nice solution, although it worked for me. Basically you read the xlsx multiple times, and remove the not necessary worksheets. This way formatting is preserved for me.

async function excelTest() {
    await workbook.xlsx.readFile('test.xlsx').then(async function(){
        workbook.eachSheet(async function(worksheet, sheetId) {
            let newWorkbook = new exceljs.Workbook();
            await newWorkbook.xlsx.readFile('test.xlsx').then(async function(){
                newWorkbook.eachSheet(function(newSheet, newSheetId){
                    if (sheetId != newSheetId) {
                        newWorkbook.removeWorksheet(newSheetId);
                    }
                });
                await newWorkbook.xlsx.writeFile(sheetId + '.xlsx');
            });
        });
    });
}
const ExcelJS = require('exceljs');

const sourceWb = new ExcelJS.Workbook();

filename = "abc.xlsx";
const fl = async () => {
    sourceWb.xlsx.readFile(filename)
        .then(async function() {
            sourceWorksheet = sourceWb.getWorksheet('tab1');
            var targetWorkbook = new Excel.Workbook;
            var targetSheet = targetWorkbook.addWorksheet('newtab');
            targetSheet.model = Object.assign(sourceWorksheet.model, {
                mergeCells: sourceWorksheet.model.merges
            });
            targetSheet.name = 'newtab';
            targetWorkbook.xlsx.writeFile('target.xlsx');


        });
}

you can try model.merges

Related