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

78 lines
2.4 KiB
Markdown
Raw Normal View History

2023-06-25 09:36:58 +00:00
---
sidebar_position: 8
title: Workbook Helpers
2024-01-03 06:47:00 +00:00
hide_table_of_contents: true
2023-06-25 09:36:58 +00:00
---
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
2024-01-03 06:47:00 +00:00
var wb_sans_sheets = XLSX.utils.book_new();
2023-06-25 09:36:58 +00:00
```
2024-01-03 06:47:00 +00:00
With no arguments, the `book_new` utility function creates an empty workbook.
:::info pass
2023-06-25 09:36:58 +00:00
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
2024-01-03 06:47:00 +00:00
:::
_Single Worksheet_
:::tip pass
Version `0.20.1` introduced the one and two argument forms of `book_new`. It is
strongly recommended to [upgrade](/docs/getting-started/installation/).
:::
```js
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.
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
```