Using the xlsx
library (based on SheetJS
), I am able to generate an Excel file with specific column orders and custom headers. Here is how I create custom headers:
const finalHeaders = [
[
this.tr.instant('shared.targetLanguage') as string,
'No Items',
this.tr.instant('reports.summarized.withoutimages') as string,
this.tr.instant('reports.summarized.creativewrd') as string,
this.tr.instant('reports.summarized.noncreativewrd') as string,
this.tr.instant('shared.client') as string,
this.tr.instant('shared.project') as string,
this.tr.instant('shared.sourceLanguage') as string,
],
];
/** Generate the excel file */
const workBook = XLSX.utils.book_new();
XLSX.utils.sheet_add_aoa(workBook, finalHeaders);
const workSheet = XLSX.utils.sheet_add_json(workBook, data, { origin: 'A2', skipHeader: true });
XLSX.utils.book_append_sheet(workBook, workSheet, 'Sheet 1'); // add the worksheet to the book
XLSX.writeFile(workBook, `Quantitative_Summarized_Report_${new Date().toLocaleString()}.xlsx`);
After generating the Excel file, I need to sort the columns in a specific order without losing the custom headers. This can be achieved by sorting the columns while preserving the custom headers:
const sortedHeader = ['clientName', 'projectName', 'sourceLanguageName', 'targetLanguageName', 'numItems', 'numItemsWithoutImages', 'numWordsCreative', 'numWordsNonCreative'];
const workSheet = XLSX.utils.json_to_sheet(data, { header: finalHeaders });
Is there a way to combine these two solutions seamlessly? Thank you in advance.