2.4 KiB
sidebar_position | title | hide_table_of_contents |
---|---|---|
8 | Workbook Helpers | true |
Many utility functions return worksheet objects. Worksheets cannot be written to workbook file formats directly. They must be added to a workbook object.
Create a new workbook
var wb_sans_sheets = XLSX.utils.book_new();
With no arguments, the book_new
utility function creates an empty workbook.
:::info pass
Spreadsheet software generally require at least one worksheet and enforce the requirement in the user interface. For example, if the last worksheet is deleted in the program, Apple Numbers will automatically create a new blank sheet.
The SheetJS write functions enforce the requirement. They will throw errors when trying to export empty workbooks.
:::
Single Worksheet
:::tip pass
Version 0.20.1
introduced the one and two argument forms of book_new
. It is
strongly recommended to upgrade.
:::
var wb_with_sheet_named_Sheet1 = XLSX.utils.book_new(worksheet);
var wb_with_sheet_named_Blatte = XLSX.utils.book_new(worksheet, "Blatte");
book_new
can accept one or two arguments.
If provided, the first argument is expected to be a worksheet object. It will be added to the new workbook.
If provided, the second argument is the name of the worksheet. If omitted, the default name "Sheet1" will be used.
Append a Worksheet to a Workbook
XLSX.utils.book_append_sheet(workbook, worksheet, sheet_name);
The book_append_sheet
utility function appends a worksheet to the workbook.
The third argument specifies the desired worksheet name. Multiple worksheets can
be added to a workbook by calling the function multiple times. If the worksheet
name is already used in the workbook, it will throw an error.
Append a Worksheet to a Workbook and find a unique name
var new_name = XLSX.utils.book_append_sheet(workbook, worksheet, name, true);
If the fourth argument is true
, the function will start with the specified
worksheet name. If the sheet name exists in the workbook, a new worksheet name
will be chosen by finding the name stem and incrementing the counter.
XLSX.utils.book_append_sheet(workbook, sheetA, "Sheet2", true); // Sheet2
XLSX.utils.book_append_sheet(workbook, sheetB, "Sheet2", true); // Sheet3
XLSX.utils.book_append_sheet(workbook, sheetC, "Sheet2", true); // Sheet4
XLSX.utils.book_append_sheet(workbook, sheetD, "Sheet2", true); // Sheet5