Создание excel файла javascript
At Dixie we are working with financial data, and a lot of our customers need the ability to easily export and work with these data. The de-facto tool to do advanced work with numeric data is Excel. That should be easy to support, we thought. “Let’s build CSV export and unicorns will dance on the clouds,” we said. “Not so fast,” screamed Excel, “you know there’s no universal CSV standard, right?”
And hell broke lose.
I am certainly over-dramatizing here, but the problem is that there isn’t just one universal Excel-supported CSV format. Various version of Excel would expect different encoding, field delimiters, number formats, etc.
We recognize that users can import CSV into a spreadsheet, specifying delimiters and such in a wizard. But we’re always striving to make our software support our customers, so we wanted their data to be one click away.
Based on these drawbacks we decided to take the road down Excel Av. and build XLSX export from our web app.
We had a very simple set of requirements:
XLS or XLSX
Since we decided that CSV wasn’t good enough, XLS or XLSX would be the way to go. XLSX would be preferable, since it’s spec is open sourced and supported widely.
No server
Minor bundle size
Doing stuff like this on the client means that they have to download more code, in order to build the file they’re about to download. While we’re utilizing load-on-demand through code-splitting, we still wanted to keep the bundle size hit low.
Looking for a XLSX JavaScript lib, which works in browsers appeared to be a challenging task. We found one lib, js-xlsx, which touted browser support, but found that it was simply too large for our need. It looks like a solid lib, but with way too many features than we needed.
So we abandoned this search and decided to research the ability to simply build the XLSX ourselves.
It seemed like a straight-forward task. We’re working with an open source technology, so we assumed that a specification would be easy to find and follow. We quickly learned that we had been naive with this regard.
XLSX is not easy to find a complete and easy to digest specification of.
We looked a placed, but never really found a quick guide to the basics of a XLSX document structure. So after having spent a few days in the blind, we decided to reverse-engineer the XLSX structure. With the knowledge that a XLSX file was simply a zip archive, we unzipped it and looked into the various files and folders.
From this surgery and trial and error, we could conclude which files are required for a XLSX file to be valid. It could be constrained to only 5 files:
- [Content_Types].xml
- _rels/.rels
- xl/_rels/workbook.xml.rels
- xl/workbook.xml
- xl/worksheets/sheet1.xml
Well, we thought that we couldn’t be the only ones, who wanted to have a simple way to export data from JavaScript to Excel. So we build a little library and have open sourced it. We named it zipcelx.
It is lightweight (7kb) and simple.
It has one API: generateAndDownloadXlsx(config) where config is an object like this:
Sheet data is basically a matrix representing the cells in a spreadsheet; an array or rows, containing an array of cells.
We currently support two data types: string and number. They’re the essentials to spreadsheets.
We build this pretty swiftly, but we are quite confident with it. But do feel free to leave any suggestions, comments or questions in a GitHub issue.
I am a nodejs programmer . Now I have a table of data that I want to save in Excel File format . How do I go about doing this ?
I found a few Node libraries . But most of them are Excel Parsers rather than Excel Writers .I am using a Linux Server . Hence need something that can run on Linux . Please let me know if there are any helpful libraries that you know of .
Or is there a way I can convert a CSV file to an xls file ( programmatically ) ?
11 Answers 11
excel4node is a maintained, native Excel file creator built from the official specification. It's similar to, but more maintained than mxexcel-builder mentioned in the other answer.
I receive an error Error: Cannot find module 'excel4node', and installed it with npm install before used
@tamilselvans Use an array.forEach(value, index) and worksheet.cell(column, row).string(value) . Bette yet read the docs!
I just figured a simple way out . This works -
Just create a file with Tabs as delimiters ( similar to CSV but replace comma with Tab ). Save it with extension .XLS . The file can be opened in Excel .
Some code to help --
This creates the file in XLS file format . It doesnt work if you try XLSX instead of XLS .
Why not use commas and create a CSV file with node and then import it into Excel? This way Excel can do its thing and create the xls/xlsx file properly.
"This creates the file in XLS file format." No it doesn't. It's still a CSV file and not capable of doing excel things,eg, multiple worksheets.
Use msexcel-builder. Install it with:
This is an excellent answer (unlike the current marked answer, which doesn't create an Excel file at all) but mxexcel-builder hasn't had any updates for four years. I've added an answer using excel4node below.
I am getting this warning in console when run their sample code from npm: (node:11702) [DEP0013] DeprecationWarning: Calling an asynchronous function without callback is deprecated.
Although this question has several answers, they may now be a little dated.
New readers may prefer to consider the xlsx or "sheetsJS" package, which now seems to now be by far the most popular node package for this use case.
The current top answer recommends excel4node , which does look quite good - but the latter package seems less maintained (and far less popular) than the former.
Answering the question directly, using xlsx:
For some people excel4node will be easier to grasp, especially if you come from the JQuery world were you chain things. But JQuery is dying for a good reason and XLSX is a much cleaner way of doing things, and gives alot more control.
You should check ExcelJS
Works with CSV and XLSX formats.
Great for reading/writing XLSX streams. I've used it to stream an XLSX download to an Express response object, basically like this:
Works great for large files, performs much better than excel4node (got huge memory usage & Node process "out of memory" crash after nearly 5 minutes for a file containing 4 million cells in 20 sheets) since its streaming capabilities are much more limited (does not allows to "commit()" data to retrieve chunks as soon as they can be generated)
В этой статье приведены примеры кода, в которых показано, как выполнять стандартные задачи для книг с использованием API JavaScript для Excel. Полный список свойств Workbook и методов, поддерживаемых объектом, см. в книге Объект (API JavaScript для Excel). В этой статье также рассматриваются действия на уровне книги, выполняемые с помощью объекта Application.
Объект Workbook — это точка входа для вашей надстройки для взаимодействия с Excel. Он поддерживает коллекции листов, таблиц, сводных таблиц и других элементов, через которые выполняется доступ и изменение данных Excel. Объект WorksheetCollection предоставляет надстройке доступ ко всем данным книги с помощью отдельных листов. В частности, он позволяет надстройке добавлять листы, перемещаться между ними и назначать обработчиков событий листа. В статье Работа с листами с использованием API JavaScript для Excel описывается способ доступа к листам и их изменение.
Получение активной ячейки или выделенного диапазона
Объект Workbook содержит два метода для получения диапазона ячеек, выделенных пользователем или надстройкой: getActiveCell() и getSelectedRange() . getActiveCell() получает активную ячейку из книги в виде объекта Range. В приведенном ниже примере показан вызов getActiveCell() с последующей печатью адреса ячейки в консоль.
Метод getSelectedRange() возвращает один диапазон, выделенный в настоящее время. Если выделено несколько диапазонов, возникает ошибка InvalidSelection. В приведенном ниже примере показан вызов метода getSelectedRange() , который затем устанавливает желтый цвет заливки для диапазона.
Создание книги
Ваша надстройка может создать новую книгу, отдельную от экземпляра Excel, в котором в настоящее время работает надстройка. Для этой цели в объекте Excel имеется метод createWorkbook . При вызове этого метода сразу открывается и отображается новая книга в новом экземпляре программы Excel. Ваша надстройка остается открытой и запущенной в предыдущей книге.
С помощью метода createWorkbook также можно создать копию существующей книги. Метод принимает в качестве необязательного параметра строковое представление XLSX-файла в кодировке base64. Полученная книга будет копией этого файла, предполагая, что строковый аргумент является допустимым XLSX-файлом.
Текущую книгу надстройки можно получить в качестве строки с кодом base64 с помощью нарезки файлов. Преобразование файла в нужную строку в кодировке base64 можно выполнить с помощью класса FileReader, как показано в приведенном ниже примере.
Вставка копии существующей книги в текущую книгу.
В предыдущем примере показана новая книга, которая была создана из существующей книги. Вы также можете скопировать отдельные части или всю существующую книгу целиком в книгу, привязанную в настоящее время к вашей надстройке. В книге используется метод insertWorksheetsFromBase64 вставки копий таблиц целевой книги в себя. Файл другой книги передается как строка с кодом base64, как и вызов Excel.createWorkbook .
Метод insertWorksheetsFromBase64 поддерживается для Excel на Windows, Mac и в Интернете. Он не поддерживается для iOS. Кроме того, Excel в Интернете этот метод не поддерживает исходные таблицы с элементами PivotTable, Chart, Comment или Slicer. Если эти объекты присутствуют, insertWorksheetsFromBase64 UnsupportedFeature метод возвращает ошибку в Excel в Интернете.
В следующем примере кода показано, как вставить в текущую книгу таблицы из другой книги. Этот пример FileReader кода сначала обрабатывает файл книги с объектом и извлекает строку с кодом base64, а затем вставляет эту строку с кодом base64 в текущую книгу. Новые листы вставляются после листа с именем Sheet1. Обратите внимание [] , что он передается в качестве параметра свойства InsertWorksheetOptions.sheetNamesToInsert . Это означает, что все таблицы из целевой книги вставляются в текущую книгу.
Защита структуры книги
Надстройка может управлять возможностью пользователя по изменению структуры книги. Свойство protection объекта Workbook является объектом WorkbookProtection с методом protect() . В приведенном ниже примере показан основной сценарий переключения защиты структуры книги.
Метод protect принимает необязательный строковый параметр. Эта строка представляет пароль, необходимый пользователю для обхода защиты и изменения структуры книги.
Защиту также можно установить на уровне книги, чтобы предотвратить нежелательные изменения данных. Дополнительные сведения см. в разделе Защита данных статьи Работа с листами с использованием API JavaScript для Excel.
Дополнительные сведения о защите книги в Excel см. в статье Защита книги.
Доступ к свойствам документов
Объекты Workbook имеют доступ к метаданным файлов Office, называемым свойствами документов. Свойство properties объекта Workbook является объектом DocumentProperties, содержащим эти значения метаданных. В следующем примере показано, как установить author свойство.
Настраиваемые свойства
Также можно установить настраиваемые свойства. Объект DocumentProperties содержит свойство custom , представляющее коллекцию пар "ключ-значение" для свойств, определяемых пользователем. В приведенном ниже примере показано, как создать настраиваемое свойство с именем Introduction со значением "Hello", а затем вызвать его.
Настраиваемые свойства на уровне таблицы
Настраиваемые свойства также можно установить на уровне таблицы. Они похожи на настраиваемые свойства на уровне документов, за исключением того, что один и тот же ключ может повторяться в разных таблицах. В следующем примере показано, как создать настраиваемую свойство WorksheetGroup со значением "Альфа" на текущем таблице, а затем получить его.
Доступ к параметрам документа
Параметры книги похожи на коллекцию настраиваемых свойств. Различие заключается в том, что параметры уникальны для одного файла Excel и соединения надстройки, а свойства связаны только с файлом. В приведенном ниже примере показано, как создать параметр и получить к нему доступ.
Доступ к настройкам культуры приложений
В книге есть языковые и культурные параметры, влияющие на отображение определенных данных. Эти параметры могут помочь локализовать данные, когда пользователи надстройки делятся книгами на разных языках и культурах. Ваша надстройка может использовать анализ строк для локализации формата чисел, дат и времени в зависимости от параметров культуры системы, чтобы каждый пользователь видел данные в формате своей культуры.
Application.cultureInfo определяет параметры культуры системы как объект CultureInfo . Это содержит параметры, такие как числовой десятичной сепаратор или формат даты.
Некоторые параметры культуры можно изменить с помощью Excel пользовательского интерфейса. Параметры системы сохраняются в объекте CultureInfo . Любые локальные изменения хранятся в качестве свойств уровня приложений, например Application.decimalSeparator .
В следующем примере изменяется десятичное сепараторное течение числовой строки с "," на символ, используемый в параметрах системы.
Добавление настраиваемых XML-данных в книгу
Формат файла Excel Open XML (XLSX) позволяет надстройке внедрить настраиваемые XML-данные в книгу. Эти данные сохраняются с книгой независимо от надстройки.
Книга содержит объект CustomXmlPartCollection, являющийся списком объектов CustomXmlParts. Они предоставляют доступ к строкам XML и соответствующему уникальному идентификатору. Сохраняя эти идентификаторы как параметры, надстройка может сохранять ключи к частям XML между сеансами.
В приведенных ниже примерах показано, как использовать настраиваемые части XML. В первом блоке кода показано, как внедрять XML-данные в документ. Выполняется сохранение списка проверяющих, а затем используются параметры книги, чтобы сохранить параметр id XML для будущих извлечений. Во втором блоке показано, как получить доступ к этим XML-данным позднее. Параметр "ContosoReviewXmlPartId" загружается и передается объекту customXmlParts книги. Данные XML затем печатаются в консоль.
CustomXMLPart.namespaceUri заполняется только в том случае, если настраиваемый XML-элемент верхнего уровня содержит атрибут xmlns .
Управление режимом вычислений
Установка режима вычислений
По умолчанию Excel пересчитывает результаты формул при каждом изменении ячейки из ссылки. Производительность вашей надстройки можно улучшить путем изменения режима вычислений. У объекта Application есть свойство calculationMode типа CalculationMode . Его можно установить к следующим значениям.
- automatic : режим пересчета по умолчанию, при котором Excel вычисляет новые результаты формулы при каждом изменении соответствующих данных.
- automaticExceptTables : аналогично automatic , за исключением того, что игнорируются любые изменения значений таблиц.
- manual : вычисления выполняются только в том случае, если пользователь или надстройка запрашивает их.
Установка типа вычислений
Объект Application предоставляет метод применения немедленного пересчета. Метод Application.calculate(calculationType) запускает ручной пересчет с учетом указанного типа calculationType . Можно укаварить следующие значения.
- full : пересчет всех формул во всех открытых книгах независимо от их изменения с прошлого пересчета.
- fullRebuild : проверка зависимых формул с последующим пересчетом всех формул во всех открытых книгах независимо от их изменения с прошлого пересчета.
- recalculate : пересчет формул, которые были изменены (или помечены программным путем для пересчета) с момента последнего вычисления, и зависимых от них формул во всех активных книгах.
Временная приостановка вычисления
API Excel также позволяет надстройкам отключить вычисления до вызова RequestContext.sync() . Для этого используется suspendApiCalculationUntilNextSync() . Используйте этот метод, если ваша надстройка изменяет большие диапазоны без необходимости доступа к данным между изменениями.
Обнаружение активации книг
Ваша надстройка может обнаруживать при активации книги. Книга становится неактивной, когда пользователь переключает фокус на другую книгу, на другое приложение или (в Excel в Интернете) на другую вкладку веб-браузера. Книга активируется , когда пользователь возвращает фокус в книгу. Активация книги может вызвать функции вызова в надстройке, например освежающие данные книги.
Чтобы определить, когда книга активирована, зарегистрируйте обработник событий для события onActivated книги. Обработчики событий для onActivated события получают объект WorkbookActivatedEventArgs при пожаре события.
Событие onActivated не определяет, когда книга открывается. Это событие обнаруживает только тогда, когда пользователь переключается на уже открытую книгу.
В следующем примере кода показано, как onActivated зарегистрировать обработник событий и настроить функцию вызова.
Сохраните книгу.
Workbook.save сохраняет книгу в постоянное хранилище. Метод save принимает один необязательный saveBehavior параметр, который может быть одним из следующих значений.
- Excel.SaveBehavior.save (по умолчанию): файл будет сохранен без предварительного запроса имени файла, а также место для сохранения. Если файл не был сохранен ранее, он будет сохранен в папке по умолчанию. Если файл уже был сохранен ранее, он будет сохранен в той же папке.
- Excel.SaveBehavior.prompt : если файл не был сохранен ранее, будет предложено ввести имя файла и место для сохранения. Если файл уже был сохранен ранее, он будет сохраняться в той же папке, и никаких дополнительных действий не потребуется.
Если пользователь при запрос на сохранение отменяет операцию, save выдает исключение.
Закрытие книги.
Workbook.close закрывает книгу, а также надстройки, связанные с книгой, (приложение Excel остается открытым). Метод close принимает один необязательный closeBehavior параметр, который может быть одним из следующих значений.
This article provides code samples that show how to perform common tasks with workbooks using the Excel JavaScript API. For the complete list of properties and methods that the Workbook object supports, see Workbook Object (JavaScript API for Excel). This article also covers workbook-level actions performed through the Application object.
The Workbook object is the entry point for your add-in to interact with Excel. It maintains collections of worksheets, tables, PivotTables, and more, through which Excel data is accessed and changed. The WorksheetCollection object gives your add-in access to all the workbook's data through individual worksheets. Specifically, it lets your add-in add worksheets, navigate among them, and assign handlers to worksheet events. The article Work with worksheets using the Excel JavaScript API describes how to access and edit worksheets.
Get the active cell or selected range
The Workbook object contains two methods that get a range of cells the user or add-in has selected: getActiveCell() and getSelectedRange() . getActiveCell() gets the active cell from the workbook as a Range object. The following example shows a call to getActiveCell() , followed by the cell's address being printed to the console.
The getSelectedRange() method returns the currently selected single range. If multiple ranges are selected, an InvalidSelection error is thrown. The following example shows a call to getSelectedRange() that then sets the range's fill color to yellow.
Create a workbook
Your add-in can create a new workbook, separate from the Excel instance in which the add-in is currently running. The Excel object has the createWorkbook method for this purpose. When this method is called, the new workbook is immediately opened and displayed in a new instance of Excel. Your add-in remains open and running with the previous workbook.
The createWorkbook method can also create a copy of an existing workbook. The method accepts a base64-encoded string representation of an .xlsx file as an optional parameter. The resulting workbook will be a copy of that file, assuming the string argument is a valid .xlsx file.
You can get your add-in's current workbook as a base64-encoded string by using file slicing. The FileReader class can be used to convert a file into the required base64-encoded string, as demonstrated in the following example.
Insert a copy of an existing workbook into the current one
The previous example shows a new workbook being created from an existing workbook. You can also copy some or all of an existing workbook into the one currently associated with your add-in. A Workbook has the insertWorksheetsFromBase64 method to insert copies of the target workbook's worksheets into itself. The other workbook's file is passed as a base64-encoded string, just like the Excel.createWorkbook call.
The insertWorksheetsFromBase64 method is supported for Excel on Windows, Mac, and the web. It's not supported for iOS. Additionally, in Excel on the web this method doesn't support source worksheets with PivotTable, Chart, Comment, or Slicer elements. If those objects are present, the insertWorksheetsFromBase64 method returns the UnsupportedFeature error in Excel on the web.
The following code sample shows how to insert worksheets from another workbook into the current workbook. This code sample first processes a workbook file with a FileReader object and extracts a base64-encoded string, and then it inserts this base64-encoded string into the current workbook. The new worksheets are inserted after the worksheet named Sheet1. Note that [] is passed as the parameter for the InsertWorksheetOptions.sheetNamesToInsert property. This means that all the worksheets from the target workbook are inserted into the current workbook.
Protect the workbook's structure
Your add-in can control a user's ability to edit the workbook's structure. The Workbook object's protection property is a WorkbookProtection object with a protect() method. The following example shows a basic scenario toggling the protection of the workbook's structure.
The protect method accepts an optional string parameter. This string represents the password needed for a user to bypass protection and change the workbook's structure.
Protection can also be set at the worksheet level to prevent unwanted data editing. For more information, see the Data protection section of the Work with worksheets using the Excel JavaScript API article.
For more information about workbook protection in Excel, see the Protect a workbook article.
Access document properties
Workbook objects have access to the Office file metadata, which is known as the document properties. The Workbook object's properties property is a DocumentProperties object containing these metadata values. The following example shows how to set the author property.
Custom properties
You can also define custom properties. The DocumentProperties object contains a custom property that represents a collection of key-value pairs for user-defined properties. The following example shows how to create a custom property named Introduction with the value "Hello", then retrieve it.
Worksheet-level custom properties
Custom properties can also be set at the worksheet level. These are similar to document-level custom properties, except that the same key can be repeated across different worksheets. The following example shows how to create a custom property named WorksheetGroup with the value "Alpha" on the current worksheet, then retrieve it.
Access document settings
A workbook's settings are similar to the collection of custom properties. The difference is settings are unique to a single Excel file and add-in pairing, whereas properties are solely connected to the file. The following example shows how to create and access a setting.
Access application culture settings
A workbook has language and culture settings that affect how certain data is displayed. These settings can help localize data when your add-in's users are sharing workbooks across different languages and cultures. Your add-in can use string parsing to localize the format of numbers, dates, and times based on the system culture settings so that each user sees data in their own culture's format.
Application.cultureInfo defines the system culture settings as a CultureInfo object. This contains settings like the numerical decimal separator or the date format.
Some culture settings can be changed through the Excel UI. The system settings are preserved in the CultureInfo object. Any local changes are kept as Application-level properties, such as Application.decimalSeparator .
The following sample changes the decimal separator character of a numerical string from a ',' to the character used by the system settings.
Add custom XML data to the workbook
Excel's Open XML .xlsx file format lets your add-in embed custom XML data in the workbook. This data persists with the workbook, independent of the add-in.
A workbook contains a CustomXmlPartCollection, which is a list of CustomXmlParts. These give access to the XML strings and a corresponding unique ID. By storing these IDs as settings, your add-in can maintain the keys to its XML parts between sessions.
The following samples show how to use custom XML parts. The first code block demonstrates how to embed XML data in the document. It stores a list of reviewers, then uses the workbook's settings to save the XML's id for future retrieval. The second block shows how to access that XML later. The "ContosoReviewXmlPartId" setting is loaded and passed to the workbook's customXmlParts . The XML data is then printed to the console.
CustomXMLPart.namespaceUri is only populated if the top-level custom XML element contains the xmlns attribute.
Control calculation behavior
Set calculation mode
By default, Excel recalculates formula results whenever a referenced cell is changed. Your add-in's performance may benefit from adjusting this calculation behavior. The Application object has a calculationMode property of type CalculationMode . It can be set to the following values.
- automatic : The default recalculation behavior where Excel calculates new formula results every time the relevant data is changed.
- automaticExceptTables : Same as automatic , except any changes made to values in tables are ignored.
- manual : Calculations only occur when the user or add-in requests them.
Set calculation type
The Application object provides a method to force an immediate recalculation. Application.calculate(calculationType) starts a manual recalculation based on the specified calculationType . The following values can be specified.
- full : Recalculate all formulas in all open workbooks, regardless of whether they have changed since the last recalculation.
- fullRebuild : Check dependent formulas, and then recalculate all formulas in all open workbooks, regardless of whether they have changed since the last recalculation.
- recalculate : Recalculate formulas that have changed (or been programmatically marked for recalculation) since the last calculation, and formulas dependent on them, in all active workbooks.
For more information about recalculation, see the Change formula recalculation, iteration, or precision article.
Temporarily suspend calculations
The Excel API also lets add-ins turn off calculations until RequestContext.sync() is called. This is done with suspendApiCalculationUntilNextSync() . Use this method when your add-in is editing large ranges without needing to access the data between edits.
Detect workbook activation
Your add-in can detect when a workbook is activated. A workbook becomes inactive when the user switches focus to another workbook, to another application, or (in Excel on the web) to another tab of the web browser. A workbook is activated when the user returns focus to the workbook. The workbook activation can trigger callback functions in your add-in, such as refreshing workbook data.
To detect when a workbook is activated, register an event handler for the onActivated event of a workbook. Event handlers for the onActivated event receive a WorkbookActivatedEventArgs object when the event fires.
The onActivated event doesn't detect when a workbook is opened. This event only detects when a user switches focus back to an already open workbook.
The following code sample shows how to register the onActivated event handler and set up a callback function.
Save the workbook
Workbook.save saves the workbook to persistent storage. The save method takes a single, optional saveBehavior parameter that can be one of the following values.
- Excel.SaveBehavior.save (default): The file is saved without prompting the user to specify file name and save location. If the file has not been saved previously, it's saved to the default location. If the file has been saved previously, it's saved to the same location.
- Excel.SaveBehavior.prompt : If file has not been saved previously, the user will be prompted to specify file name and save location. If the file has been saved previously, it will be saved to the same location and the user will not be prompted.
If the user is prompted to save and cancels the operation, save throws an exception.
Close the workbook
Workbook.close closes the workbook, along with add-ins that are associated with the workbook (the Excel application remains open). The close method takes a single, optional closeBehavior parameter that can be one of the following values.
A full featured xlsx file generation library allowing for the creation of advanced Excel files.
excel4node conforms to the ECMA-376 OOXML specification 2nd edition
excel4node comes with some generic functions and types
xl.getExcelRowCol(cellRef)
Accepts cell reference (i.e. 'A1') and returns object with corresponding row and column
xl.getExcelAlpha(column)
Accepts column as integer and returns corresponding column reference as alpha
xl.getExcelCellRef(row, column)
Accepts row and column as integers and returns Excel cell reference
xl.getExcelTS(date)
Accepts Date object and returns an Excel timestamp
An instance of the Workbook class contains all data and parameters for the Excel Workbook.
Workbook constructor accepts an optional configuration object.
wb.addWorksheet(name, options);
Adds a new Worksheet to the Workbook
Accepts name of new Worksheet and options object (see Worksheet section)
Returns a Worksheet instance
wb.setSelectedTab(id);
Sets which tab will be selected when the Workbook is opened
Accepts Sheet ID (1-indexed sheet in order that sheets were added)
wb.createStyle(opts);
Creates a new Style instance
Accepts Style configuration object (see Style section) Returns a new Style instance
wb.writeToBuffer();
The writeToBuffer() method access no parameters and returns a promise that resolves with the nodebuffer generated by the JSZip library. This buffer can then be sent to other streams.
An instance of the Worksheet class contains all information specific to that worksheet
Worksheet constructor is called via Workbook class and accepts a name and configuration object
Full Worksheet options. All options are optional.
Note: headerFooter strings accept Dynamic Formatting Strings. i.e. '&L&A&C&BCompany, Inc. Confidential&B&RPage &P of &N'
Worksheet data validations
ws.addDataValidation();
Accepts a validation options object with these available options. All options are optional with exception of sqref.
Worksheet Conditional Formatting
Conditional formatting adds custom formats in response to cell reference state. A subset of conditional formatting features is currently supported by excel4node.
Formatting rules apply at the worksheet level.
The following example will highlight all cells between A1 and A10 that contain the string "ok" with bold, green text:
The only conditional formatting type that is currently supported is expression.
When the formula returns zero, conditional formatting is NOT displayed. When the formula returns a nonzero value, conditional formatting is displayed.
Worksheet Page Breaks
Worksheet page breaks can be added at rows and columns
ws.addPageBreak(type, position) where type is row or column and position is the last row/column before the page break.
Worksheet Print Area
Worksheet print areas can be set
ws.setPrintArea(startRow, startCol, endRow, endCol) where parameters are numbers corresponding to print area
Rows and Columns
Set custom widths and heights of columns/rows
Set rows and/or columns to create a frozen pane with an optionall scrollTo
Add Filters to a row If not options are given to the filter function, a filter will be added to all columns that contain data. Optionally, if you wish to restrict your filter to a specific range, you can specify start and end rows and columns for that range. The filter row should be included in this range.
Hide a row or column
Create groupings of rows or columns and optionally state to collapse the grouping
Multiple groupings can be nested as demonstrated in this gist
Style objects can be applied to Cells
Any combination of style values can be set
Creating a preset style is much more efficient than applying styles to individual cells
Comments can be added to cells with some options
Adds and image to the worksheet.
currently on 'picture' type is supported
positioning has 3 types, 'absoluteAnchor', 'oneCellAnchor', 'twoCellAnchor'
absoluteAnchor takes two position elements in either EMUs or measurements in cm, mm, or in
x:0, y:0 is top left corner of worksheet
oneCellAnchor and twoCellAnchor types will take positional objects:
position type of oneCellAnchor will take a single "from" position
position type of twoCellAnchor will take a "from" and "to" position
specifying a twoCellAnchor will automatically adjust the image to fit within the bounds of the two anchors.
Читайте также: