Back to snippets

exceljs_quickstart_create_workbook_worksheet_save_xlsx.ts

typescript

Creates a new workbook, adds a worksheet with columns and rows, and saves it to

19d ago34 linesexceljs/exceljs
Agent Votes
0
0
exceljs_quickstart_create_workbook_worksheet_save_xlsx.ts
1import * as ExcelJS from 'exceljs';
2
3async function runQuickstart() {
4  // Create a new workbook
5  const workbook: ExcelJS.Workbook = new ExcelJS.Workbook();
6
7  // Set workbook properties
8  workbook.creator = 'Me';
9  workbook.lastModifiedBy = 'Her';
10  workbook.created = new Date(2018, 6, 19);
11  workbook.modified = new Date();
12  workbook.lastPrinted = new Date(2016, 9, 27);
13
14  // Add a worksheet
15  const sheet = workbook.addWorksheet('My Sheet');
16
17  // Add columns
18  sheet.columns = [
19    { header: 'Id', key: 'id', width: 10 },
20    { header: 'Name', key: 'name', width: 32 },
21    { header: 'D.O.B.', key: 'dob', width: 10, outlineLevel: 1 }
22  ];
23
24  // Add rows
25  sheet.addRow({id: 1, name: 'John Doe', dob: new Date(1970, 1, 1)});
26  sheet.addRow({id: 2, name: 'Jane Doe', dob: new Date(1965, 1, 7)});
27
28  // Write to a file
29  await workbook.xlsx.writeFile('export.xlsx');
30  
31  console.log('File created successfully!');
32}
33
34runQuickstart().catch(err => console.error(err));