How to merge worksheets of different workbooks in one workbook ? #2053
Replies: 1 comment 1 reply
-
@shubhamseth29 Hello, I bumped into something similar today. I hope this is still relevant for you. I needed to merge two CSV files with the same structure. Here's how I've done it.
const workbook = new Excel.Workbook();
const sheet = workbook.addWorksheet(sheetName);
for await (const [index, file] of files.entries()) {
const fileWorkbook = new Excel.Workbook();
const oldSheet = await fileWorkbook.csv.read(file);
if (index === 0) {
// Here we add header row just once. We also use `compact` from `lodash` to remove any empty rows
// Row numbers start from 1
sheet.addRow(compact(castArray(oldSheet.getRow(1).values as any[])));
}
// Here we map rows from `old` files
const oldRows = oldSheet
.getRows(2, oldSheet.rowCount)
.map((row) => row.values) // That why it wasn't working, need to extract only `values`
.map((row) => JSON.parse(JSON.stringify(row)));
oldRows.forEach((row) => {
if (row.length === 0) return;
// In my case it was adding empty value at start of each row, so I used slice
const newRow = (row as any[]).slice(1).map((el) => {
return el === null ? '' : el;
});
sheet.addRow(newRow);
});
}
This is an interesting case. If we console log any row it will output Without this row all empty rows will be missed in final file which will break the structure. So after parse and stringify those values will be replaced by
const pass = new stream.PassThrough();
workbook.csv.write(pass, {
sheetName: sheetName,
dateFormat: 'DD/MM/YYYY',
});
return pass; So that's pretty much it. Tested it in my case and it's working. |
Beta Was this translation helpful? Give feedback.
-
Hi ,
I want to generate a combined excel workbook , where in I want to merge all different excel sheets into one.
Currently I am doing something of this sort
Beta Was this translation helpful? Give feedback.
All reactions