xlsx-populate

repository·master·Indexed 21 days ago

https://github.com/dtjohnson/xlsx-populate

A JavaScript Excel XLSX parser and generator for Node.js and browser environments. It features jQuery/d3-style method chaining and focuses on preserving existing workbook features and styles. Key capabilities include creating new workbooks, parsing existing files, manipulating cell ranges, managing worksheets, applying cell styles and formatting, and configuring print options and page margins.

Tokens
27.9K
Snippets
104
Records
138
Agent score
73%

What's inside xlsx-populate

  1. How xlsx-populate works

    master

    xlsx-populate operates by manipulating the underlying XML structure of an XLSX workbook rather than deserializing the entire file into a rich object model.

    An XLSX workbook is a zip archive of XML files. The library uses JSZip to unzip the workbook and sax-js to parse the XML documents into objects. As you call methods, xlsx-populate manipulates these objects directly. When generating output, it uses xmlbuilder-js to convert the objects back to XML and JSZip to re-zip them.

    Key Benefit: Because it manipulates the XML data directly instead of attempting to map the entire Office Open XML specification to a high-level model, it can preserve styles and other content that the library does not explicitly support, preventing data loss during the read/write cycle.

  2. Manipulate cell ranges

    master

    You can work with multiple cells at once using range(address).

    • Set values: Use .value() with a single value, a 2D array, or a callback function (cell, ri, ci, range) => value.
    • Bulk extraction: Use Sheet.usedRange().value() to get a 2D array of all values in a worksheet.
    • Top-left shortcut: Setting a value on a single cell with a 2D array will populate the range starting from that cell.
    // Get 2D array of all values in the worksheet.
    const values = workbook.sheet("Sheet1").usedRange().value();
    
    // Set values using a 2D array in a range:
    r.value([
        [1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]
    ]);
  3. Work with cell ranges

    master

    Ranges allow you to parse or manipulate multiple cells simultaneously. You can create a range using .range("A1:C3") on a sheet.

    Setting values in a range:

    • Single value: r.value(5) sets all cells to 5.
    • 2D Array: r.value([[1, 2], [3, 4]]) maps values to the grid.
    • Callback: r.value((cell, ri, ci, range) => Math.random()) allows per-cell logic.
    • Top-left shortcut: Calling .value() on the top-left cell of a range with a 2D array will populate the range.

    Extracting values: Use Sheet.usedRange().value() to quickly retrieve a 2D array of all values in a worksheet.

    const r = workbook.sheet(0).range("A1:C3");
    
    // Set all cell values to the same value:
    r.value(5);
    
    // Set the values using a 2D array:
    r.value([
        [1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]
    ]);
    
    // Set the values using a callback function:
    r.value((cell, ri, ci, range) => Math.random());
    
    // Get 2D array of all values in the worksheet.
    const values = workbook.sheet("Sheet1").usedRange().value();
  4. Set up the development environment

    master

    To contribute to or develop xlsx-populate, ensure you have the following installed:

    • Node.js: version 4 or higher (required for ES6 syntax).
    • git: for version control.
    • gulp: installed globally via npm.

    Initial Setup Steps:

    1. Install gulp globally:
      npm install -g gulp
    2. Clone the repository and install dependencies:
      npm install
    3. Run the default gulp task to watch files and run tests:
      gulp
    4. To build the project for the browser:
      gulp build
    npm install -g gulp
    npm install
    gulp
    gulp build
  5. Populate and parse Excel data

    master

    To manipulate Excel workbooks, you first load one using fromBlankAsync() (for a new workbook), fromFileAsync() (from an existing file), or fromDataAsync() (from a Blob or ArrayBuffer).

    Populating: Access sheets and cells to set values. Use .value(val) on a cell or range.

    Parsing: Use .value() without arguments on a cell to retrieve its content.

    Note on Formulas: For cells containing formulas, xlsx-populate returns the calculated value stored in the workbook at the time of saving. It does not recalculate formulas during manipulation or write new calculated values to the output.

    const XlsxPopulate = require('xlsx-populate');
    
    // Load a new blank workbook
    XlsxPopulate.fromBlankAsync()
        .then(workbook => {
            // Modify the workbook.
            workbook.sheet("Sheet1").cell("A1").value("This is neat!");
    
            // Write to file.
            return workbook.toFileAsync("./out.xlsx");
        });
  6. Install xlsx-populate for the Browser

    master

    There are several ways to include xlsx-populate in a browser project:

    1. Bower: Install the package using bower. Once included, the module is available globally as XlsxPopulate.
    2. Browserify: Require the module using browserify. Because the library uses ES6 features, you must use babelify with babel-preset-env to transpile the code for browser compatibility.
    3. Manual Download: You can download the combined, minified code directly from the browser directory in the repository.
    bower install xlsx-populate
  7. Pull Request Checklist for contributors

    master

    Before submitting a pull request, ensure your code meets these requirements:

    • Pattern: Follow the getter/setter pattern using a single function for both (distinguish via arguments.length or ArgHandler).
    • Documentation: Use valid JSDoc on all methods and classes. Use @private for private methods and @ignore for internal public methods.
    • Linting: Adhere to ESLint rules (run gulp lint).
    • Syntax: Use ES6 syntax.
    • Testing: Provide full Jasmine unit test coverage and ensure all tests pass.
    • Stability: Do not modify or break existing API behavior (the project follows semantic versioning).
    • Docs: If the feature requires more than JSDoc, update docs/template.md.
  8. Use xlsx-populate in the Browser

    master

    The library is exposed globally as XlsxPopulate in the browser.

    Loading Data

    • From File Input: Use XlsxPopulate.fromDataAsync(file) where file is a File object from an <input type="file">.
    • From AJAX: Set the XMLHttpRequest.responseType to 'arraybuffer' and pass the response to XlsxPopulate.fromDataAsync(req.response).

    Downloading Data

    You can export the workbook as a Blob (default) or a Base64 string.

    • Blob (Recommended): Use workbook.outputAsync() to get a Blob, then create an object URL and a temporary <a> element to trigger a download. (Note: IE requires window.navigator.msSaveOrOpenBlob).
    • Base64: Use workbook.outputAsync("base64") and set location.href to a data URI. Note: This is not supported in IE.
    // Download as Blob (standard browsers)
    workbook.outputAsync()
        .then(function (blob) {
            var url = window.URL.createObjectURL(blob);
            var a = document.createElement("a");
            a.href = url;
            a.download = "out.xlsx";
            a.click();
            window.URL.revokeObjectURL(url);
        });
  9. Set up a development environment for xlsx-populate

    master

    To contribute to or develop for xlsx-populate, ensure you have the following installed:

    1. Node.js: Version 4 or higher (required for ES6 syntax).
    2. Git: For version control.
    3. Gulp: Installed globally via npm.

    Installation Steps

    From the project root, install the necessary npm dependencies:

    npm install

    Running the Development Workflow

    • Watch for changes: Run gulp to start the default task, which watches source files for updates and runs tests automatically. If you add new files, you must restart gulp to include them in the watch list.
    • Build for the browser: To create the client-side JavaScript bundle, run:
    gulp build
  10. Populate data in a new workbook

    master

    To create a new Excel file, use XlsxPopulate.fromBlankAsync(). You can then access sheets and cells to set values and finally write the workbook to a file using workbook.toFileAsync().

    const XlsxPopulate = require('xlsx-populate');
    
    // Load a new blank workbook
    XlsxPopulate.fromBlankAsync()
        .then(workbook => {
            // Modify the workbook.
            workbook.sheet("Sheet1").cell("A1").value("This is neat!");
    
            // Write to file.
            return workbook.toFileAsync("./out.xlsx");
        });