### Install write-excel-file using npm Source: https://gitlab.com/catamphetamine/write-excel-file/-/blob/main/README.md Install the package using npm. It can also be included via a script tag in web pages. ```bash npm install write-excel-file --save ``` -------------------------------- ### Example Usage of Sensitivity Labels Feature Source: https://gitlab.com/catamphetamine/write-excel-file/-/blob/main/README_FEATURE_SENSITIVITY_LABEL.md Demonstrates how to use the sensitivity labels feature when writing an Excel file. Requires providing the sensitivity label ID, site ID, and optionally assignment method and content bits. ```javascript // An example of using this feature. await writeXlsxFile(data, { // The unique GUID (Globally Unique Identifier) of the sensitivity label itself, // which is specific to an organization's Microsoft Purview configuration. // // Common Sensitivity Label ID Examples (based on Microsoft Information Protection examples): // * Personal: 73c47c6a-eb00-4a6a-8e19-efaada66dee6 // * Public: 73254501-3d5b-4426-979a-657881dfcb1e // * General: da480625-e536-430a-9a9e-028d16a29c59 // * Confidential: 569af77e-61ea-4deb-b7e6-79dc73653959 // * Highly Confidential: 905845d6-b548-439c-9ce5-73b2e06be157 // sensitivityLabelId: '569af77e-61ea-4deb-b7e6-79dc73653959', // Site ID is a unique identifier (GUID) for your organization's Microsoft 365 tenant, // required to enforce policy persistence and identify the label's source. // Example: "5f0d8a9b-e21a-4c4c-87d2-7c9d3f1a2b3c". sensitivityLabelSiteId: '5f0d8a9b-e21a-4c4c-87d2-7c9d3f1a2b3c', // The manner in which the label was assugned (e.g., manual, automatic, recommended). // // The possible values correspond to the `MsoAssignmentMethod` enumeration in Office programming interfaces and can be one of the following: // * standard — The label was manually applied by a user. // * privileged — The label was applied as a result of a privileged operation (e.g., by an administrator or a specific process). ``` -------------------------------- ### Positioning an Image with Anchor Cell Source: https://gitlab.com/catamphetamine/write-excel-file/-/blob/main/docs/IMAGES.md Specifies how to anchor an image to a specific cell within the spreadsheet using `row` and `column` properties. Row and column numbers start from 1. ```javascript { content, contentType, width, height, anchor: { // Row number, starting from 1. row: number, // Column number, starting from 1. column: number } } ``` -------------------------------- ### Get Order of Siblings for XML Insertion Source: https://gitlab.com/catamphetamine/write-excel-file/-/blob/main/README.md Use `getOrderOfSiblings` to retrieve the `orderOfSiblings` array required by `insertElementMarkupAccordingToOrderOfSiblings`. Note that support is limited to specific file and top-level tag names. ```javascript import { getOrderOfSiblings } from 'write-excel-file/utility'; const order = getOrderOfSiblings('sheet.xml', 'parent1'); console.log(order); ``` -------------------------------- ### Find Element in XML String Source: https://context7.com/catamphetamine/write-excel-file/llms.txt Locates a specific XML element within an XML string. Returns an object with start and end positions, useful for further manipulation. ```javascript import { findElement } from 'write-excel-file/utility' // --- XML manipulation inside a feature's transform function --- const xmlBefore = `` // Find an element const sheetViewElement = findElement(xmlBefore, 'sheetView') // sheetViewElement is an object with .start, .end, etc. ``` -------------------------------- ### Include via CDN Source: https://gitlab.com/catamphetamine/write-excel-file/-/blob/main/README.md Include the library using a script tag from a CDN. Then, use the `writeXlsxFile` function to create an Excel file. ```html ``` -------------------------------- ### Run Test Case and Write Excel File Source: https://gitlab.com/catamphetamine/write-excel-file/-/blob/main/website/test-cases.html Handles the click event for the 'runTestCaseButton'. It retrieves the selected test case ID, extracts its arguments, and then uses 'writeXlsxFile.apply' to generate an Excel file named 'spreadsheet.xlsx'. Includes basic error handling. ```javascript const runTestCaseButton = document.getElementById('runTestCaseButton') runTestCaseButton.addEventListener('click', function() { const testCaseId = testCasesSelect.value const testCase = TEST_CASES.default[testCaseId] const [arg1, arg2, ...argsRest] = testCase.args() writeXlsxFile.apply(this, [arg1, arg2, ...argsRest]).toFile('spreadsheet.xlsx').then( () => { // console.log('File created') }, (error) => { console.error(error) alert('There was an error. See console output for the error stack trace.') } ) }) ``` -------------------------------- ### Get Child Elements of an XML Element Source: https://gitlab.com/catamphetamine/write-excel-file/-/blob/main/README.md Use `getChildElements` to retrieve all direct child elements of a given XML element. This is useful for iterating over the children of a node. ```javascript import { getChildElements } from 'write-excel-file/utility'; const xml = ''; const parentElement = findElement(xml, 'parent'); const childElements = getChildElements(xml, parentElement); console.log(childElements); ``` -------------------------------- ### Write Excel File with Columns Parameter (New API) Source: https://gitlab.com/catamphetamine/write-excel-file/-/blob/main/CHANGELOG.md Shows how to use the new `columns` parameter in `writeExcelFile()` as an alternative to the removed `schema` parameter for defining column configurations. ```javascript await writeExcelFile(objects, { columns }) ``` -------------------------------- ### Get XML Markup Inside an Element Source: https://gitlab.com/catamphetamine/write-excel-file/-/blob/main/README.md Use `getMarkupInsideElement` to extract the XML content that is nested within a specified element. This is useful for inspecting or processing the inner structure of an element. ```javascript import { getMarkupInsideElement } from 'write-excel-file/utility'; const xml = 'inner content'; const element = 'inner content'; const markup = getMarkupInsideElement(xml, element); console.log(markup); ``` -------------------------------- ### Browser CDN Integration for Excel File Generation Source: https://context7.com/catamphetamine/write-excel-file/llms.txt Include the script from a CDN and use the global `writeXlsxFile` function to create an Excel file with specified data and options. This method is suitable for quick browser integration without a bundler. ```html ``` -------------------------------- ### Generate Opening XML Tag Source: https://gitlab.com/catamphetamine/write-excel-file/-/blob/main/README.md Use `getOpeningTagMarkup` to create the XML markup for an opening tag with specified attributes. This is helpful for constructing XML dynamically. ```javascript import { getOpeningTagMarkup } from 'write-excel-file/utility'; const markup = getOpeningTagMarkup('tag', { attribute: 'value' }); console.log(markup); ``` -------------------------------- ### Write Excel File with Multiple Sheets (New API) Source: https://gitlab.com/catamphetamine/write-excel-file/-/blob/main/CHANGELOG.md Demonstrates the new API for writing an Excel file with multiple sheets, where each sheet's configuration is provided as an object within a single array argument. ```javascript await writeExcelFile([ { data: data1, sheet: 'Sheet1', columns: columns1, ... }, { data: data2, sheet: 'Sheet2', columns: columns2, ... } ]) ``` -------------------------------- ### Establish Sensitivity Label Relationship Source: https://gitlab.com/catamphetamine/write-excel-file/-/blob/main/README_FEATURE_SENSITIVITY_LABEL.md Establish a relationship between the document and the sensitivity labels definition file in the _rels/.rels file. The Target should point to the sensitivity labels definition file. ```xml ... ``` -------------------------------- ### Write Excel File with getSheetData (New API) Source: https://gitlab.com/catamphetamine/write-excel-file/-/blob/main/CHANGELOG.md Demonstrates using the `getSheetData()` function in conjunction with `writeExcelFile()` as an alternative to the `schema` parameter for preparing sheet data. ```javascript await writeExcelFile(getSheetData(objects, schema)) ``` -------------------------------- ### Write sheet data to a file in the browser Source: https://gitlab.com/catamphetamine/write-excel-file/-/blob/main/README.md Import 'write-excel-file/browser' to trigger a 'Save as' dialog for the user to save the generated XLSX file. ```javascript import writeExcelFile from 'write-excel-file/browser' await writeExcelFile(sheetData).toFile('file.xlsx') ``` -------------------------------- ### Write Workbook with Multiple Sheets Source: https://context7.com/catamphetamine/write-excel-file/llms.txt Create a workbook with multiple sheets by passing an array of sheet descriptor objects to `writeExcelFile`. Each descriptor includes `data`, `sheet` name, `columns` options, and `stickyRowsCount`. ```javascript import writeExcelFile from 'write-excel-file/node' const summaryData = [ [{ value: 'Quarter', fontWeight: 'bold' }, { value: 'Revenue', fontWeight: 'bold' }], ['Q1', 120000], ['Q2', 135000], ['Q3', 98000], ['Q4', 160000] ] const detailData = [ [{ value: 'Month', fontWeight: 'bold' }, { value: 'Amount', fontWeight: 'bold' }], ['January', 40000], ['February', 38000], ['March', 42000] ] await writeExcelFile([ { data: summaryData, sheet: 'Summary', columns: [{ width: 12 }, { width: 14 }], stickyRowsCount: 1 }, { data: detailData, sheet: 'Detail', columns: [{ width: 12 }, { width: 14 }], stickyRowsCount: 1 } ]).toFile('./report.xlsx') ``` -------------------------------- ### Adding Images to write-excel-file Options Source: https://gitlab.com/catamphetamine/write-excel-file/-/blob/main/docs/IMAGES.md Shows how to pass an array of image objects to the `writeXlsxFile` function via the `options` argument. Ensure images are not part of the main data array. ```javascript const images = [{ ... }, { ... }] const row1 = [cell1, cell2] const data = [row1, row2] await writeXlsxFile(data, { images }) ``` -------------------------------- ### Convert Objects to Sheet Data and Write to File (Node.js) Source: https://gitlab.com/catamphetamine/write-excel-file/-/blob/main/README.md Utilize the Node.js specific module to first convert objects to sheet data using `getSheetData`, then write the data to an Excel file. This approach allows for explicit control over the sheet data generation and file writing process, including applying column widths. ```javascript import writeExcelFile, { getSheetData } from 'write-excel-file/node' // Convert `objects` to `sheetData`. const sheetData = getSheetData(objects, columns) // Write `sheetData` to an ".xslx" file. // Also pass the `columns` here to apply the column `width`. ``` ```javascript await writeExcelFile(sheetData, { columns }).toFile(...) ``` -------------------------------- ### Import write-excel-file in Node.js (v2.x) Source: https://gitlab.com/catamphetamine/write-excel-file/-/blob/main/README.md This is the old import method for Node.js environments before version 3.x. ```javascript import writeExcelFile from "write-excel-file" ``` -------------------------------- ### Create basic sheet data for XLSX Source: https://gitlab.com/catamphetamine/write-excel-file/-/blob/main/README.md Sheet data should be an array of rows, where each row is an array of cells. Cells can be strings, numbers, booleans, Dates, or null for empty cells. ```javascript const sheetData = [ ['A','B','C'], // 1st row ['x',123,true], // 2nd row ['y',456,false] // 3rd row ] ``` -------------------------------- ### Basic Data Structure for write-excel-file Source: https://gitlab.com/catamphetamine/write-excel-file/-/blob/main/docs/IMAGES.md Illustrates the standard data format for rows and cells when using the write-excel-file function without images. ```javascript const row1 = [cell1, cell2] const data = [row1, row2] await writeXlsxFile(data) ``` -------------------------------- ### Update files.transform.insert options Source: https://gitlab.com/catamphetamine/write-excel-file/-/blob/main/README.md Properties like `multipleSheetsParameters`, `attributeValue()`, and `textContent()` are removed from the second argument of `files.transform.insert()`. Import utilities directly. ```javascript import { attributeValue, textContent } from 'write-excel-file/utility' ``` -------------------------------- ### Update files.transform.insert arguments Source: https://gitlab.com/catamphetamine/write-excel-file/-/blob/main/README.md The first argument for `files.transform.insert()` and `files.transform.transform()` is now an array of sheet options. ```javascript files.transform.insert([ { data: sheetData1, ... }, { data: sheetData2, ... } ]) ``` -------------------------------- ### Update files.write.files arguments Source: https://gitlab.com/catamphetamine/write-excel-file/-/blob/main/README.md The first argument for `files.write.files()` is now an array of sheet options. ```javascript files.write.files([ { data: sheetData1, ... }, { data: sheetData2, ... } ]) ``` -------------------------------- ### Initialize Object Data for Excel Source: https://gitlab.com/catamphetamine/write-excel-file/-/blob/main/website/index.html Sets the initial JSON value for the 'objects' textarea, formatting it for readability. It replaces placeholder dates with actual Date objects. ```javascript document.getElementById('objects').value = JSON.stringify(\[ { name: 'John Smith', dateOfBirth: 999999999999999, income: 120000, married: true }, { name: 'Alice Brown', dateOfBirth: 999999999999999, income: 60000, married: false } \], null, 2).replace(/999999999999999/g, 'new Date()') ``` -------------------------------- ### Schema Column Definition (New API) Source: https://gitlab.com/catamphetamine/write-excel-file/-/blob/main/CHANGELOG.md Illustrates the updated schema format where the `column` property has been renamed to `header`, and `header` can now be an object to define cell styles. ```javascript [{ header: 'First Name', value: (person) => person.firstName }] ``` -------------------------------- ### Configure Sensitivity Label Properties Source: https://gitlab.com/catamphetamine/write-excel-file/-/blob/main/README_FEATURE_SENSITIVITY_LABEL.md Set various properties for sensitivity labels, such as assignment method, name, set date, action ID, and content protection bits. Use 'Privileged' for the assignment method and 0 for no content protection. ```javascript sensitivityLabelAssignmentMethod: 'Privileged', // The human-readable name of the sensitivity label (e.g., "Confidential", "Public"). // Translates into `name` XML attribute. // sensitivityLabelName: ... // The timestamp of when the label was applied or last modified. // Translates into `setDate` XML attribute. // sensitivityLabelSetDate: ... // A unique identifier for the specific protective action (e.g., encryption settings) associated with the label. // Translates into `actionId` XML attribute. // Example: "d601b072-68b2-4d2a-a92e-9d2432e0e02c". // sensitivityLabelActionId: ... // An integer value representing the type of protection applied to the content (e.g., encryption). // Common ContentBits examples: // * 0 (no protection) // * 2 (encryption applied) // * 8 (content markings applied) // * combinations like 10 (encryption + marking) sensitivityLabelContentBits: 0 ``` -------------------------------- ### Populate Test Cases Dropdown Source: https://gitlab.com/catamphetamine/write-excel-file/-/blob/main/website/test-cases.html Populates a select dropdown with available test case IDs from the TEST_CASES object. Each option's text and value are set to the test case ID. ```javascript const testCasesSelect = document.getElementById('testCasesSelect') for (const testCaseId of Object.keys(TEST_CASES.default)) { const testCase = TEST_CASES.default[testCaseId] const option = document.createElement('option') option.textContent = testCaseId option.value = testCaseId testCasesSelect.appendChild(option) } ``` -------------------------------- ### Set Object Column Configuration Source: https://gitlab.com/catamphetamine/write-excel-file/-/blob/main/website/index.html Populates the 'objects-columns' textarea with a string representation of the column configuration for object-based Excel generation. ```javascript document.getElementById('objects-columns').value = ` \n\[ { header: { value: 'Name', fontWeight: 'bold' }, cell: (person) => ({ value: person.name }), width: 20 }, { header: { value: 'Date of Birth', fontWeight: 'bold' }, cell: (person) => ({ value: person.dateOfBirth, type: Date, format: 'mm/dd/yyyy' }), width: 14 }, { header: { value: 'Income', fontWeight: 'bold' }, cell: (person) => ({ value: person.income, type: Number, format: '#,##0.00' }), width: 12 }, { header: { value: 'Married', fontWeight: 'bold' }, cell: (person) => ({ value: person.married, type: Boolean }) } \n\] `.trim() ``` -------------------------------- ### Write Multi-Sheet Excel File Source: https://gitlab.com/catamphetamine/write-excel-file/-/blob/main/README.md Pass an array of sheet objects to create an Excel file with multiple sheets. Each object can define data, sheet name, columns, and sticky rows/columns. ```javascript await writeExcelFile([ { data: data1, sheet: 'Sheet 1', columns: columns1, stickyRowsCount: 1 }, { data: data2, sheet: 'Sheet 2', columns: columns2, stickyColumnsCount: 1 } ]).toFile(...) ``` -------------------------------- ### Initialize Cell Data for Excel Source: https://gitlab.com/catamphetamine/write-excel-file/-/blob/main/website/index.html Populates the 'cell-data' textarea with JSON representing data for an Excel sheet, including cell values, types, and formats. It uses placeholders for dates. ```javascript document.getElementById('cell-data').value = JSON.stringify(\[ \[ { value: 'Name', fontWeight: 'bold' }, { value: 'Date of Birth', fontWeight: 'bold' }, { value: 'Income', fontWeight: 'bold' }, { value: 'Married', fontWeight: 'bold' } \], \[ { value: 'John Smith' }, { value: 999999999999999, type: 'Date', format: 'mm/dd/yyyy' }, { value: 1800, type: 'Number', format: '#,##0.00' }, { value: true, type: 'Boolean' } \], \[ { value: 'Alice Brown' }, { value: 999999999999999, type: 'Date', format: 'mm/dd/yyyy' }, { value: 2599.99, type: 'Number', format: '#,##0.00' }, { value: false, type: 'Boolean' } \] \], null, 2).replace(/999999999999999/g, 'new Date()') .replace(/"type": \"(\[^",\]+)\" /g, '"type": $1') ``` -------------------------------- ### Write to Blob using Universal Module Source: https://gitlab.com/catamphetamine/write-excel-file/-/blob/main/README.md Use the universal module to write sheet data to a Blob. This method is compatible with both web browsers and Node.js environments. ```javascript import writeExcelFile from 'write-excel-file/universal' const blob = await writeExcelFile(sheetData).toBlob() ``` -------------------------------- ### Enable and Use Sensitivity Labels Feature Source: https://gitlab.com/catamphetamine/write-excel-file/-/blob/main/README_FEATURE_SENSITIVITY_LABEL.md Enable the sensitivity labels feature by including `sensitivityLabelsFeature` in the `features` array. This configuration is used when writing an Excel file. ```javascript // Use the sensitivity labels feature. features: [sensitivityLabelsFeature] }) // Output to file. .toFile('/path/to/output-file.xlsx') ``` -------------------------------- ### Write Excel File to File Path (New API) Source: https://gitlab.com/catamphetamine/write-excel-file/-/blob/main/CHANGELOG.md Illustrates the updated method for writing an Excel file to a specified file path using the `toFile()` method, which is part of the returned object from `writeExcelFile()`. ```javascript await writeExcelFile(data).toFile('/path/to/output-file.xlsx') ``` -------------------------------- ### Configure Sheet Options for Excel File Source: https://context7.com/catamphetamine/write-excel-file/llms.txt Use sheet options to control layout, formatting, and visibility for a single sheet. Specify orientation, date format, frozen rows/columns, grid lines, zoom, and column widths. ```javascript import writeExcelFile from 'write-excel-file/node' const data = [ [{ value: 'ID', fontWeight: 'bold' }, { value: 'Name', fontWeight: 'bold' }, { value: 'Date', fontWeight: 'bold' }], [1, 'Alice', new Date('2024-01-10')], [2, 'Bob', new Date('2024-02-20')] ] await writeExcelFile(data, { sheet: 'Staff Report', orientation: 'landscape', // 'portrait' (default) | 'landscape' dateFormat: 'dd/mm/yyyy', // default format for all Date cells stickyRowsCount: 1, // freeze the first row (header) stickyColumnsCount: 1, // freeze the first column (ID) showGridLines: false, // hide grid lines zoomScale: 1.25, // 125% zoom rightToLeft: false, // set true for Arabic / Hebrew layouts columns: [ { width: 6 }, { width: 18 }, { width: 14 } ] }).toFile('./staff.xlsx') ``` -------------------------------- ### Define Sensitivity Labels XML Source: https://gitlab.com/catamphetamine/write-excel-file/-/blob/main/README_FEATURE_SENSITIVITY_LABEL.md Define the sensitivity labels to be applied to the document in a separate .xml file. Replace placeholders with actual values. ```xml ``` -------------------------------- ### Update writeExcelFile for single sheet options Source: https://gitlab.com/catamphetamine/write-excel-file/-/blob/main/README.md Options like `fontFamily`, `fontSize`, and `features` are now passed as a third argument to `writeExcelFile()`. ```javascript await writeExcelFile(data, null, { fontFamily, fontSize, features }) ``` -------------------------------- ### Add Sensitivity Label Content Type Override Source: https://gitlab.com/catamphetamine/write-excel-file/-/blob/main/README_FEATURE_SENSITIVITY_LABEL.md Add an element for the sensitivity labels .xml file in the [Content_Types].xml file. Ensure the PartName matches the file path. ```xml ... ``` -------------------------------- ### Import write-excel-file in Browser (v3.x) Source: https://gitlab.com/catamphetamine/write-excel-file/-/blob/main/README.md When migrating from v2.x to v3.x, the default export for browser usage is now located at 'write-excel-file/browser'. This version utilizes Web Workers. ```javascript import writeExcelFile from "write-excel-file/browser" ``` -------------------------------- ### Write sheet data to a Buffer in Node.js Source: https://gitlab.com/catamphetamine/write-excel-file/-/blob/main/README.md Generate an XLSX file as a Buffer, suitable for memory-based operations or sending over networks in Node.js. ```javascript const buffer = await writeExcelFile(sheetData).toBuffer() ``` -------------------------------- ### Set header style using schema header property Source: https://gitlab.com/catamphetamine/write-excel-file/-/blob/main/README.md The `getHeaderStyle` parameter is removed. Use the new `header` property on each column in the schema to style header cells. ```javascript { header: { value: 'ID', style: { fontWeight: 'bold' } }, key: 'id' } ``` -------------------------------- ### Write to Blob (Browser) Source: https://context7.com/catamphetamine/write-excel-file/llms.txt In the browser, this function triggers a 'Save As' dialog or returns a Blob. It uses Web Workers for non-blocking operations. Ensure the correct import for browser usage. ```javascript import writeExcelFile from 'write-excel-file/browser' const sheetData = [ ['Name', 'Score'], ['Alice', 95], ['Bob', 87] ] // Trigger browser "Save As" dialog await writeExcelFile(sheetData).toFile('results.xlsx') // Or get a Blob for further use (e.g. upload to server) const blob = await writeExcelFile(sheetData).toBlob() const formData = new FormData() formData.append('file', blob, 'results.xlsx') await fetch('/upload', { method: 'POST', body: formData }) ``` -------------------------------- ### Content Types for Images and Drawings Source: https://gitlab.com/catamphetamine/write-excel-file/-/blob/main/docs/IMAGES.md Add default extensions for common image types and override for custom types. Also, include an entry for each drawing file, which represents all images on a specific sheet. ```xml ... ... ``` -------------------------------- ### AWS S3 workaround for stream length Source: https://gitlab.com/catamphetamine/write-excel-file/-/blob/main/README.md When uploading to AWS S3 using SDK v2, use a Buffer instead of a stream for the 'Body' to avoid 'Cannot determine length' errors. ```javascript await new AWS.S3().putObject({ Bucket: '...', Key: '...', Body: readStream, ContentType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }).promise() ``` -------------------------------- ### Generate Closing XML Tag Source: https://gitlab.com/catamphetamine/write-excel-file/-/blob/main/README.md Use `getClosingTagMarkup` to create the XML markup for a closing tag. This is a simple utility for XML construction. ```javascript import { getClosingTagMarkup } from 'write-excel-file/utility'; const markup = getClosingTagMarkup('tag'); console.log(markup); ``` -------------------------------- ### Write Objects to Excel File with Custom Columns Source: https://gitlab.com/catamphetamine/write-excel-file/-/blob/main/README.md Directly write an array of objects to an Excel file using a defined column structure. This simplifies the process by handling the conversion from objects to sheet data internally. ```javascript await writeExcelFile(objects, { columns }).toFile(...) ``` -------------------------------- ### Define Sensitivity Labels Feature Source: https://gitlab.com/catamphetamine/write-excel-file/-/blob/main/README_FEATURE_SENSITIVITY_LABEL.md Defines the structure and logic for integrating sensitivity labels. This includes specifying which files to transform and write, and the XML content to be inserted or generated based on provided parameters. ```javascript import { sanitizeAttributeValue } from 'write-excel-file/utility' // Constants. const sensitivityLabelsDefinitionFilePath = 'docMetadata/LabelInfo.xml' const sensitivityLabelsRelationshipId = 'rId-sensitivityLabels-1' const sensitivityLabelsFeature = { // Describes the files that this feature will transform or write. files: { // Describes the files that this feature will transform. transform: { // This feature will transform "[Content_Types].xml" file. '[Content_Types].xml': { // It will insert additional XML markup inside the root element. insert: ({ sensitivityLabelId, sensitivityLabelSiteId, sensitivityLabelAssignmentMethod, sensitivityLabelContentBits }) => { // If `sensitivityLabelId` parameter is passed. if (sensitivityLabelId) { // Return the additional XML markup that will be inserted inside the root element. return `` } } }, // This feature will transform "_rels/.rels" file. '_rels/.rels': { // It will insert additional XML markup inside the root element. insert: ({ sensitivityLabelId, sensitivityLabelSiteId, sensitivityLabelAssignmentMethod, sensitivityLabelContentBits }) => { // If `sensitivityLabelId` parameter is passed. if (sensitivityLabelId) { // Return the additional XML markup that will be inserted inside the root element. return `` } } } }, // Describes the files that this feature will write. write: { // It will write some "global" files, i.e. ones that're shared between all sheets. files: ({ sensitivityLabelId, sensitivityLabelSiteId, sensitivityLabelAssignmentMethod, sensitivityLabelContentBits }) => { // If `sensitivityLabelId` parameter is passed. if (sensitivityLabelId) { // Validate `sensitivityLabelSiteId` parameter value. if (!sensitivityLabelSiteId) { throw new Error('When `sensitivityLabelId` parameter is specified, `sensitivityLabelSiteId` parameter must be specified too') } // Validate `sensitivityLabelContentBits` parameter value. if (sensitivityLabelContentBits !== undefined && typeof sensitivityLabelContentBits !== 'number') { throw new Error('When `sensitivityLabelContentBits` parameter is specified, it should be a number') } // Return the list of "global" files that will be written. return { [sensitivityLabelsDefinitionFilePath]: '' + '' + `` + '' } } } } } } ``` -------------------------------- ### Define Objects for Sheet Data Conversion Source: https://gitlab.com/catamphetamine/write-excel-file/-/blob/main/README.md Prepare an array of JavaScript objects to be converted into Excel sheet data. Each object represents a row, and its properties correspond to column values. ```javascript // These objects should be written to an ".xlsx" file const objects = [ { name: 'John Smith', dateOfBirth: new Date(Date.UTC(2000, 1 - 1, 5)), income: 120000, married: true }, { name: 'Alice Brown', dateOfBirth: new Date(Date.UTC(2005, 4 - 1, 3)), income: 60000, married: false } ] ``` -------------------------------- ### Implement Custom Feature for Excel File Source: https://gitlab.com/catamphetamine/write-excel-file/-/blob/main/README.md Import the `Feature` interface and implement a custom feature to extend the package's functionality. This allows modification of XML files within the Excel archive. ```typescript // Import a TypeScript interface called `Feature`. import type { Feature } from 'write-excel-file/node' // This is an implementation of a custom "feature". // It must implement the `Feature` TypeScript interface. const myCustomFeature: Feature = { ... } await writeExcelFile( data, { sheet: 'Sheet Name' }, { features: [myCustomFeature] } ).toFile(...) ``` -------------------------------- ### Write sheet data to an XLSX file in Node.js Source: https://gitlab.com/catamphetamine/write-excel-file/-/blob/main/README.md Use the default export with the '/node' path to write sheet data to a file. Ensure the sheetData variable is defined. ```javascript import writeExcelFile from 'write-excel-file/node' await writeExcelFile(sheetData).toFile('/path/to/output-file.xlsx') ``` -------------------------------- ### Define header cell style in schema Source: https://gitlab.com/catamphetamine/write-excel-file/-/blob/main/README.md The `header` property in a schema can now be an object to define the header cell's value and style properties. ```javascript { header: { value: 'First Name', fontWeight: 'bold' }, value: (person) => person.firstName } ``` -------------------------------- ### Specify width for Date columns Source: https://gitlab.com/catamphetamine/write-excel-file/-/blob/main/README.md The default `width: 14` for `type: Date` columns is removed. Specify the width manually in the schema. ```javascript { header: 'Date', type: 'date', width: 20 } ``` -------------------------------- ### Write Raw Sheet Data to File (Node.js) Source: https://context7.com/catamphetamine/write-excel-file/llms.txt Writes a 2D array of cell values to an .xlsx file in Node.js. Supports writing to disk, a Buffer, or a stream. Ensure the correct import for Node.js. ```javascript import writeExcelFile from 'write-excel-file/node' const sheetData = [ [ { value: 'Order ID', fontWeight: 'bold' }, { value: 'Amount', fontWeight: 'bold' }, { value: 'Date', fontWeight: 'bold' }, { value: 'Paid', fontWeight: 'bold' } ], [ { value: 1001 }, { value: 1234.56, type: Number, format: '[$$-409]#,##0.00', backgroundColor: '#FFFF00' }, { value: new Date('2024-03-15'), type: Date, format: 'mm/dd/yyyy' }, { value: true, type: Boolean } ], [ { value: 1002 }, { value: 789.00, type: Number, format: '[$$-409]#,##0.00' }, { value: new Date('2024-03-16'), type: Date, format: 'mm/dd/yyyy' }, { value: false, type: Boolean } ] ] // Writes to disk; returns void await writeExcelFile(sheetData, { sheet: 'Orders' }).toFile('./orders.xlsx') // Write to a Buffer (e.g. for HTTP response) const buffer = await writeExcelFile(sheetData).toBuffer() // buffer instanceof Buffer === true // Write to a readable stream const readStream = await writeExcelFile(sheetData).toStream() readStream.pipe(process.stdout) // Write to a writable stream import fs from 'fs' const writeStream = fs.createWriteStream('./orders.xlsx') await writeExcelFile(sheetData).toStream(writeStream) ``` -------------------------------- ### Write Excel File from Objects Source: https://gitlab.com/catamphetamine/write-excel-file/-/blob/main/website/index.html Generates an 'objects.xlsx' file from JSON data in the 'objects' textarea. It parses the JSON, converts date placeholders, and applies column configurations. ```javascript document.getElementById('write-xlsx-file-button-objects').addEventListener('click', () => { try { const objects = JSON.parse( document.getElementById('objects').value .replace(/new Date\(\)/g, '999999999999999') ) for (const object of objects) { for (const key of Object.keys(object)) { if (object[key] === 999999999999999) { object[key] = new Date() } } } writeXlsxFile(objects, { columns: columnsWhenUsingObjects }).toFile('objects.xlsx').then( () => { // console.log('File created') }, (error) => { console.error(error) alert('There was an error. See console output for the error stack trace.') } ) } catch (error) { console.error(error) alert("There was an error. See console output for the error stack trace.") } }) ``` -------------------------------- ### Babel Runtime Dependency in Node.js Source: https://gitlab.com/catamphetamine/write-excel-file/-/blob/main/README.md This dependency is used in Node.js environments for polyfilling async/await support in older Node.js versions. It can be removed if the code is refactored without async/await. ```javascript import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; import _regeneratorRuntime from "@babel/runtime/regenerator"; ``` -------------------------------- ### Schema Cell Properties (New API) Source: https://gitlab.com/catamphetamine/write-excel-file/-/blob/main/CHANGELOG.md Shows the new structure for defining cell properties within a schema, where properties like `value`, `type`, and `format` are nested under a `cell` object. ```javascript cell: (object, objectIndex) => ({ value: object.firstName, type: String, format: '@', fontWeight: 'bold' }) ``` -------------------------------- ### Customize cell appearance and format Source: https://gitlab.com/catamphetamine/write-excel-file/-/blob/main/README.md Represent cells as objects to customize their appearance, such as currency formatting and background color. The 'format' property uses Excel format strings. ```javascript [ ['Order ID', 'Amount'], [1, { value: 1234.56, format: '[$$-409]#,##0.00', backgroundColor: '#FFFF00' }], [2, { value: 789, format: '[$$-409]#,##0.00' }] ] ``` -------------------------------- ### Positioning an Image with Offset Source: https://gitlab.com/catamphetamine/write-excel-file/-/blob/main/docs/IMAGES.md Allows for precise image placement by defining an offset in pixels relative to the anchor cell. Supports both horizontal (`offsetX`) and vertical (`offsetY`) adjustments. ```javascript { content, contentType, width, height, anchor: { row: number, column: number }, // Horizontal offset, in pixels. offsetX?: number, // Horizontal offset, in pixels. offsetY?: number } ``` -------------------------------- ### Image Relationship in Drawing XML Source: https://gitlab.com/catamphetamine/write-excel-file/-/blob/main/docs/IMAGES.md Define a relationship for each image file within the drawing's XML relationships file. The 'Id' attribute links to the image in the media folder. ```xml ... ``` -------------------------------- ### Add Image Relationship Source: https://gitlab.com/catamphetamine/write-excel-file/-/blob/main/docs/IMAGES.md Define the relationship for a drawing in the spreadsheet's relationships file. This is a prerequisite for inserting an image. ```xml ``` -------------------------------- ### Build Safe XML Markup Source: https://context7.com/catamphetamine/write-excel-file/llms.txt Generates XML opening, closing, or self-closing tags with attributes, ensuring that attribute names and values are properly escaped for safe XML construction. ```javascript import { getOpeningTagMarkup, getClosingTagMarkup, getSelfClosingTagMarkup } from 'write-excel-file/utility' // Build XML markup safely const openTag = getOpeningTagMarkup('c', { r: 'A1', t: 'n' }) // → '' const closeTag = getClosingTagMarkup('c') // → '' const selfClose = getSelfClosingTagMarkup('col', { min: '1', max: '1', width: '12' }) // → '' ``` -------------------------------- ### Generate Self-Closing XML Tag Source: https://gitlab.com/catamphetamine/write-excel-file/-/blob/main/README.md Use `getSelfClosingTagMarkup` to create the XML markup for a self-closing tag with attributes. Useful for elements that do not contain content. ```javascript import { getSelfClosingTagMarkup } from 'write-excel-file/utility'; const markup = getSelfClosingTagMarkup('tag', { attribute: 'value' }); console.log(markup); ``` -------------------------------- ### Write sheet data to a writable Stream in Node.js Source: https://gitlab.com/catamphetamine/write-excel-file/-/blob/main/README.md Pipe the XLSX data directly into a writable stream, such as a file stream. ```javascript const writeStream = fs.createWriteStream('/path/to/output-file.xlsx') await writeExcelFile(sheetData).toStream(writeStream) ``` -------------------------------- ### Define Columns for Object to Sheet Data Conversion Source: https://gitlab.com/catamphetamine/write-excel-file/-/blob/main/README.md Define the structure for converting objects to sheet data, including headers, cell formatting, and column widths. This configuration is used by the `writeExcelFile` function when processing object arrays. ```javascript // These columns should be written to the ".xlsx" file const columns = [ { header: getHeader('Name'), cell: (person) => ({ value: person.name }), width: 20 // `width` is optional and is measured in characters }, { header: getHeader('Date of Birth'), cell: (person) => ({ value: person.dateOfBirth, type: Date, // `type` is optional and will be derived from `value` format: 'mm/dd/yyyy' }) }, { header: getHeader('Income'), cell: (person) => ({ value: person.income, type: Number, // `type` is optional and will be derived from `value` format: '#,##0.00' }) }, { header: getHeader('Married'), cell: (person) => ({ value: person.married, type: Boolean // `type` is optional and will be derived from `value` }) } ] // Helper function: creates a header cell object const getHeader = (text) => ({ value: text, fontWeight: 'bold' }) ``` -------------------------------- ### Set Global Font Options for Excel File Source: https://context7.com/catamphetamine/write-excel-file/llms.txt Apply global font properties like family and size to all sheets. For single-sheet files, these are the third argument; for multi-sheet files, they are the second argument. ```javascript import writeExcelFile from 'write-excel-file/node' const data = [['Hello', 'World'], [1, 2]] await writeExcelFile( data, { sheet: 'Sheet1' }, // sheet options (2nd arg) { fontFamily: 'Calibri', fontSize: 11 } ).toFile('./global-font.xlsx') // Multi-sheet: global options as 2nd arg await writeExcelFile( [ { data: [['A', 'B'], [1, 2]], sheet: 'One' }, { data: [['C', 'D'], [3, 4]], sheet: 'Two' } ], { fontFamily: 'Arial', fontSize: 10 } // global options (2nd arg) ).toFile('./multi-global.xlsx') ``` -------------------------------- ### Generated Sheet Data from Objects and Columns Source: https://gitlab.com/catamphetamine/write-excel-file/-/blob/main/README.md Illustrates the structure of `sheetData` generated from an array of objects and a column configuration. This format is used internally by the library for writing Excel files. ```javascript [ [ { value: 'Name', fontWeight: 'bold' }, { value: 'Date of Birth', fontWeight: 'bold' }, { value: 'Income', fontWeight: 'bold' }, { value: 'Married', fontWeight: 'bold' } ], [ { value: 'John Smith' }, { value: 2000-01-05T00:00:00.000Z, type: Date, format: 'mm/dd/yyyy' }, { value: 120000, type: Number, format: '#,##0.00' }, { value: true, type: Boolean } ], [ { value: 'Alice Brown' }, { value: 2005-04-03T00:00:00.000Z, type: Date, format: 'mm/dd/yyyy' }, { value: 60000, type: Number, format: '#,##0.00' }, { value: false, type: Boolean } ] ] ``` -------------------------------- ### Set Column Widths in Excel File Source: https://gitlab.com/catamphetamine/write-excel-file/-/blob/main/README.md Configure column widths in characters when writing an Excel file. This option is applied when passing sheet data and can be combined with other writing methods. ```javascript // Set Column #3 width to "20 characters". const columns = [ {}, {}, { width: 20 }, // in characters {} ] await writeExcelFile(sheetData, { columns }).toFile(...) ``` -------------------------------- ### Update writeExcelFile for multiple sheets Source: https://gitlab.com/catamphetamine/write-excel-file/-/blob/main/README.md When writing multiple sheets, the function now accepts a single argument containing an array of sheet configuration objects. ```javascript [ { data: data1, sheet: 'Sheet1', columns: columns1, ... }, { data: data2, sheet: 'Sheet2', columns: columns2, ... } ] ```