docs.sheetjs.com/docz/docs/08-api/07-utilities/08-wb.md

52 lines
1.8 KiB
Markdown
Raw Normal View History

2023-06-25 09:36:58 +00:00
---
sidebar_position: 8
title: Workbook Helpers
---
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**
```js
var workbook = XLSX.utils.book_new();
```
The `book_new` utility function creates an empty workbook with no worksheets.
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](/docs/api/write-options) enforce the requirement.
2023-06-25 19:57:03 +00:00
They will throw errors when trying to export empty workbooks.
2023-06-25 09:36:58 +00:00
**Append a Worksheet to a Workbook**
```js
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_
```js
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
2023-06-25 19:57:03 +00:00
will be chosen by finding the name stem and incrementing the counter.
2023-06-25 09:36:58 +00:00
```js
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
```