excelize-wasm

repository·main·Indexed 43 days ago

https://github.com/xuri/excelize-wasm

A WebAssembly and JavaScript port of the Go Excelize library for reading, writing, and manipulating Office Excel documents (XLSX, XLSM, XLAM, XLTM, XLTX) in the browser or Node.js. Version 0.1.3 provides APIs for creating spreadsheets via NewFile(), reading via OpenReader(), adding charts with AddChart(), and inserting images with AddPictureFromBytes(), along with utility functions for cell coordinate conversion and color mapping.

Tokens
22.3K
Snippets
61
Records
95
Agent score
55%

What's inside excelize-wasm

  1. Initialize excelize-wasm

    main

    To use the library, you must first initialize it by providing the path to the compressed WebAssembly file (excelize.wasm.gz). The init function returns a promise that resolves to the excelize instance.

    In Node.js, the path is typically ./node_modules/excelize-wasm/excelize.wasm.gz. In a browser, you must provide the full URL to the hosted .wasm.gz file.

    const { init } = require('excelize-wasm');
    
    init('./node_modules/excelize-wasm/excelize.wasm.gz').then((excelize) => {
      // Use excelize instance here
    });
  2. Install excelize-wasm

    main

    You can install excelize-wasm via npm for Node.js environments or include it via a <script> tag for browser environments.

    Node.js

    npm install --save excelize-wasm

    Browser

    <script src="excelize-wasm/index.js"></script>
  3. Environment requirements for excelize-wasm

    main

    The library requires certain global APIs to be present in the environment. If they are missing, you must provide polyfills:

    • globalThis.crypto: Specifically crypto.getRandomValues is required.
    • globalThis.performance: Specifically performance.now is required.
    • globalThis.TextEncoder: Required for string encoding.
    • globalThis.TextDecoder: Required for string decoding.

    In Node.js environments, the library attempts to automatically polyfill crypto and performance using built-in modules.

  4. Access the excelize JavaScript API

    main

    When the WebAssembly module is loaded, it registers an excelize object on the global scope (window in browsers or global in other environments). This object provides access to various spreadsheet manipulation functions and constants.

    All functions in the excelize object follow a similar pattern: they take arguments from JavaScript, perform the operation using the underlying Go excelize library, and return results as JavaScript objects or values. Errors are typically returned as part of the result object (e.g., { "error": "error message" }).

  5. Initialize the excelize-wasm library

    main

    To use the library, you must first initialize it by providing the path to the WASM file using the init function. This function handles loading the WASM binary (including decompression if necessary), setting up the Go runtime environment, and attaching the excelize API to the globalThis object.

    Note: The init function is asynchronous and returns the excelize object which contains the library's public API.

    import { init } from 'excelize-wasm';
    
    const excelize = await init('path/to/excelize.wasm');
    // Now you can use the excelize API
  6. Initialize the Excelize WASM module

    main

    To use the library, you must first call the init function. This function compiles and instantiates the WebAssembly code from a provided compressed .wasm archive path. It returns a Promise that resolves to an object containing all the API methods and constant enums (like ChartType, CellType, etc.) required to manipulate spreadsheets.

    Note that the returned object contains the full suite of tools, including coordinate conversion utilities, file creation methods, and various type enums.

    import { init } from 'excelize-wasm';
    
    const excelize = await init('/path/to/excelize.wasm');
    // Now you can use excelize.NewFile(), excelize.OpenReader(), etc.
  7. Set worksheet scaling and print options

    main

    You can control how a worksheet is scaled for printing using SetSheetProps and SetPageLayout. There are four common scaling presets:

    1. No Scaling (Actual size): Set FitToPage: false via SetSheetProps.

    2. Fit Sheet on One Page (Shrink to fit one page): Set FitToPage: true via SetSheetProps.

    3. Fit All Columns on One Page (One page wide): Set FitToPage: true via SetSheetProps and set FitToHeight: 0 via SetPageLayout.

    4. Fit All Rows on One Page (One page high): Set FitToPage: true via SetSheetProps and set FitToWidth: 0 via SetPageLayout.

    // 1. No Scaling
    const { error } = f.SetSheetProps('Sheet1', {
      FitToPage: false,
    });
    
    // 2. Fit Sheet on One Page
    const { error } = f.SetSheetProps('Sheet1', { FitToPage: true });
    
    // 3. Fit All Columns on One Page
    let { error } = f.SetSheetProps('Sheet1', { FitToPage: true });
    ({ error } = f.SetPageLayout('Sheet1', { FitToHeight: 0 }));
    
    // 4. Fit All Rows on One Page
    let { error } = f.SetSheetProps('Sheet1', { FitToPage: true });
    ({ error } = f.SetPageLayout('Sheet1', { FitToWidth: 0 }));
  8. Read an existing spreadsheet

    main

    To read an existing file, use excelize.OpenReader(buffer) where buffer is the file content (e.g., from fs.readFileSync).

    Key methods for reading:

    • GetCellValue(sheet, cell): Retrieves the value of a specific cell. Returns an object with { value, error }.
    • GetRows(sheet): Retrieves all rows in a sheet. Returns an object with { result, error }, where result is an array of arrays representing rows and columns.
    const { init } = require('excelize-wasm');
    const fs = require('fs');
    
    init('./node_modules/excelize-wasm/excelize.wasm.gz').then((excelize) => {
      const f = excelize.OpenReader(fs.readFileSync('Book1.xlsx'));
      if (f.error) {
        console.log(f.error);
        return;
      }
      // Get cell value
      const ret1 = f.GetCellValue('Sheet1', 'B2');
      if (ret1.error) {
        console.log(ret1.error);
        return;
      }
      console.log(ret1.value);
    
      // Get all rows
      const ret2 = f.GetRows('Sheet1');
      if (ret2.error) {
        console.log(ret2.error);
        return;
      }
      ret2.result.forEach((row) => {
        row.forEach((colCell) => {
          process.stdout.write(`${colCell}\t`);
        });
        console.log();
      });
    });
  9. Add a chart to a spreadsheet

    main

    You can generate charts based on worksheet data using f.AddChart(sheet, cell, options).

    Key Options:

    • Type: The chart type (e.g., excelize.Col3DClustered).
    • Series: An array of objects defining Name, Categories, and Values (using Excel-style range strings like Sheet1!$B$1:$D$1).
    • Title: An object containing Paragraph information for the chart title.

    Example

    const ret3 = f.AddChart('Sheet1', 'E1', {
      Type: excelize.Col3DClustered,
      Series: [
        {
          Name: 'Sheet1!$A$2',
          Categories: 'Sheet1!$B$1:$D$1',
          Values: 'Sheet1!$B$2:$D$2',
        },
        // ... more series
      ],
      Title: { Paragraph: [{ Text: 'Fruit 3D Clustered Column Chart' }] },
    });
    const { init } = require('excelize-wasm');
    const fs = require('fs');
    
    init('./node_modules/excelize-wasm/excelize.wasm.gz').then((excelize) => {
      const f = excelize.NewFile();
      if (f.error) {
        console.log(f.error);
        return;
      }
      [
        [null, 'Apple', 'Orange', 'Pear'],
        ['Small', 2, 3, 3],
        ['Normal', 5, 2, 4],
        ['Large', 6, 7, 8],
      ].forEach((row, idx) => {
        const ret1 = excelize.CoordinatesToCellName(1, idx + 1);
        if (ret1.error) {
          console.log(ret1.error);
          return;
        }
        const res2 = f.SetSheetRow('Sheet1', ret1.cell, row);
        if (res2.error) {
          console.log(res2.error);
          return;
        }
      });
      const ret3 = f.AddChart('Sheet1', 'E1', {
        Type: excelize.Col3DClustered,
        Series: [
          {
            Name: 'Sheet1!$A$2',
            Categories: 'Sheet1!$B$1:$D$1',
            Values: 'Sheet1!$B$2:$D$2',
          },
          {
            Name: 'Sheet1!$A$3',
            Categories: 'Sheet1!$B$1:$D$1',
            Values: 'Sheet1!$B$3:$D$3',
          },
          {
            Name: 'Sheet1!$A$4',
            Categories: 'Sheet1!$B$1:$D$1',
            Values: 'Sheet1!$B$4:$D$4',
          },
        ],
        Title: { Paragraph: [{ Text: 'Fruit 3D Clustered Column Chart' }] },
      });
      if (ret3.error) {
        console.log(ret3.error);
        return;
      }
      // Save spreadsheet by the given path.
      const { buffer, error } = f.WriteToBuffer();
      if (error) {
        console.log(error);
        return;
      }
      fs.writeFile('Book1.xlsx', buffer, 'binary', (error) => {
        if (error) {
          console.log(error);
        }
      });
    });
  10. Read a spreadsheet file

    main

    To read an existing spreadsheet, use excelize.OpenReader(buffer) where buffer is the file content as a byte array. You can then retrieve cell values using GetCellValue or entire rows using GetRows.

    Node.js Example

    const { init } = require('excelize-wasm');
    const fs = require('fs');
    
    init('./node_modules/excelize-wasm/excelize.wasm.gz').then((excelize) => {
      const f = excelize.OpenReader(fs.readFileSync('Book1.xlsx'));
      if (f.error) {
        console.log(f.error);
        return;
      }
      // Get value of a cell.
      const ret1 = f.GetCellValue('Sheet1', 'B2');
      if (ret1.error) {
        console.log(ret1.error);
        return;
      }
      console.log(ret1.value);
    
      // Get all the rows in the Sheet1.
      const ret2 = f.GetRows('Sheet1');
      if (ret2.error) {
        console.log(ret2.error);
        return;
      }
      ret2.result.forEach((row) => {
        row.forEach((colCell) => {
          process.stdout.write(`${colCell}\t`);
        });
        console.log();
      });
    });
    const { init } = require('excelize-wasm');
    const fs = require('fs');
    
    init('./node_modules/excelize-wasm/excelize.wasm.gz').then((excelize) => {
      const f = excelize.OpenReader(fs.readFileSync('Book1.xlsx'));
      if (f.error) {
        console.log(f.error);
        return;
      }
      // Set value of a cell.
      const ret1 = f.GetCellValue('Sheet1', 'B2');
      if (ret1.error) {
        console.log(ret1.error);
        return;
      }
      console.log(ret1.value);
      // Get all the rows in the Sheet1.
      const ret2 = f.GetRows('Sheet1');
      if (ret2.error) {
        console.log(ret2.error);
        return;
      
      ret2.result.forEach((row) => {
        row.forEach((colCell) => {
          process.stdout.write(`${colCell}\t`);
        });
        console.log();
      });
    });
  11. Create a new spreadsheet workbook

    main

    Use excelize.NewFile() to create a new workbook. You can then add sheets with NewSheet(name), set cell values with SetCellValue(sheet, cell, value), and set the active sheet with SetActiveSheet(index). To save the workbook, use WriteToBuffer() to get the file contents as a buffer.

    const { init } = require('excelize-wasm');
    const fs = require('fs');
    
    init('./node_modules/excelize-wasm/excelize.wasm.gz').then((excelize) => {
      const f = excelize.NewFile();
      if (f.error) {
        console.log(f.error);
        return;
      }
      // Create a new sheet
      const { index } = f.NewSheet('Sheet2');
      // Set cell values
      f.SetCellValue('Sheet2', 'A2', 'Hello world.');
      f.SetCellValue('Sheet1', 'B2', 100);
      // Set default sheet
      f.SetActiveSheet(index);
      // Save to buffer
      const { buffer, error } = f.WriteToBuffer();
      if (error) {
        console.log(error);
        return;
      }
      fs.writeFile('Book1.xlsx', buffer, 'binary', (error) => {
        if (error) console.log(error);
      });
    });
  12. Insert pictures into a worksheet

    main

    Use f.AddPictureFromBytes(sheet, cell, options) to insert images.

    Options include:

    • Extension: The file extension (e.g., '.png', '.jpg', '.gif').
    • File: The image data as a buffer/Uint8Array.
    • Format: An object containing:
      • AltText: Alternative text for the image.
      • ScaleX, ScaleY: Scaling factors (e.g., 0.5).
      • OffsetX, OffsetY: Pixel offsets.
      • PrintObject: Boolean indicating if the image should be printed.
      • LockAspectRatio: Boolean to lock the aspect ratio.
      • Locked: Boolean to lock the image position/size.
    const { init } = require('excelize-wasm');
    const fs = require('fs');
    
    init('./node_modules/excelize-wasm/excelize.wasm.gz').then((excelize) => {
      const f = excelize.OpenReader(fs.readFileSync('Book1.xlsx'));
      if (f.error) {
        console.log(f.error);
        return;
      }
    
      // Insert picture with scaling
      const ret2 = f.AddPictureFromBytes('Sheet1', 'D2', {
        Extension: '.jpg',
        File: fs.readFileSync('image.jpg'),
        Format: { AltText: 'Picture 2', ScaleX: 0.5, ScaleY: 0.5 },
      });
      if (ret2.error) {
        console.log(ret2.error);
        return;
      }
    
      // Insert picture with print properties
      const ret3 = f.AddPictureFromBytes('Sheet1', 'H2', {
        Extension: '.gif',
        File: fs.readFileSync('image.gif'),
        Format: {
          AltText: 'Picture 3',
          OffsetX: 15,
          OffsetY: 10,
          PrintObject: true,
          LockAspectRatio: false,
          Locked: false,
        },
      });
      if (ret3.error) {
        console.log(ret3.error);
        return;
      }
    
      const { buffer, error } = f.WriteToBuffer();
      if (error) {
        console.log(error);
        return;
      }
      fs.writeFile('Book1.xlsx', buffer, 'binary', (error) => {
        if (error) console.log(error);
      });
    });