SheetJS / sheetjs

📗 SheetJS Spreadsheet Data Toolkit -- New home https://git.sheetjs.com/SheetJS/sheetjs
https://sheetjs.com/
Apache License 2.0
35.02k stars 8k forks source link

Rearranging the XLSX.write order #2804

Open HarshaKosala opened 2 years ago

HarshaKosala commented 2 years ago

Hi is it possible to write the output to the excel file as shown below? Have the headers in one column (A1) and data in another (B1).

image

Rather than the normal behavior as shown below image

itsnoa04 commented 1 year ago

Hey, its possible..

import * as XLSX from "xlsx";

// create a new workbook and worksheet
const workbook = XLSX.utils.book_new();
const worksheet = XLSX.utils.aoa_to_sheet([[]]);

// define the headers and data
const headers: string[] = ["Header1", "Header2", "Header3"];
const data: string[][] = [
  ["Data1", "Data2", "Data3"],
  ["Data4", "Data5", "Data6"],
  ["Data7", "Data8", "Data9"],
];

// add the headers to the worksheet
XLSX.utils.sheet_add_aoa(
  worksheet,
  headers.map((header) => [header]),
  { origin: "A1" }
);

// add the data to the worksheet
XLSX.utils.sheet_add_aoa(worksheet, data, { origin: "B1" });

// add the worksheet to the workbook
XLSX.utils.book_append_sheet(workbook, worksheet, "Sheet1");

// write the workbook to a file
XLSX.writeFile(workbook, "output.xlsx");