DEV Community

Jeremy K.
Jeremy K.

Posted on

Extracting Images from Excel with JavaScript

Introduction

In many frontend projects, you may need to parse Excel files and batch-export images embedded in them. Most conventional approaches rely on a backend service to parse the file and return the images for the frontend to download. But if you need offline frontend parsing without involving a server, a WASM-based Excel library is a good option.

This article walks through how to use Spire.XLS for JavaScript in the browser to read an Excel workbook, extract every embedded image from a worksheet, and trigger browser downloads. The approach works well as a reference for React projects.


Approach

The overall workflow is straightforward:

  1. Load the WASM module and wait for initialization to complete.
  2. Load the Excel file into the component’s built-in virtual file system (VFS).
  3. Open the workbook and select the target worksheet.
  4. Iterate over all picture objects on the worksheet and save the images to the VFS.
  5. Read the binary data from the VFS, wrap it in a Blob, and trigger a browser download via an <a> tag.
  6. Dispose of the workbook after parsing to avoid unnecessary memory usage.

Key point: Because WASM runs in a virtual file system, exported images do not automatically appear on the local disk. You must manually read the file stream from the VFS and pass it to the frontend download logic.


Complete Example Code (React)

function App() {
  const extractAllImages = async () => {
    // Get the initialized Spire.XLS WASM module instance
    const xlsModule = window.wasmModule?.spirexls;

    // Check whether the module is ready
    if (!xlsModule) {
      alert('Spire.XLS is not ready yet');
      return;
    }

    const inputFileName = 'ReadImages.xlsx';
    // Fetch the Excel file from the public directory into the VFS
    await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}data/`);

    // Load the workbook and get the first worksheet
    const workbook = new xlsModule.Workbook();
    workbook.LoadFromFile({ fileName: inputFileName });
    const sheet = workbook.Worksheets.get(0);

    // Loop through all pictures in the current worksheet
    for (let i = 0; i < sheet.Pictures.Count; i++) {
      const pic = sheet.Pictures.get(i);
      const outputFileName = `Image-${i + 1}.png`;
      // Save the picture to the WASM virtual file system
      pic.Picture.Save(outputFileName);

      // Read the binary file from the VFS
      const fileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
      const blob = new Blob([fileArray], { type: 'image/png' });
      const url = URL.createObjectURL(blob);

      // Trigger the browser download
      const a = document.createElement('a');
      a.href = url;
      a.download = outputFileName;
      a.click();
      URL.revokeObjectURL(url);
    }

    // Dispose of the workbook to prevent memory leaks
    workbook.Dispose();
  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Extract Images from Excel</h1>
      <button onClick={extractAllImages}>
        Extract All Images
      </button>
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Key Details

1. WASM Module Initialization Timing

The first check for xlsModule is critical. WASM files are large, and loading and initialization are asynchronous, so the module may not be ready when the page finishes rendering. In production, add a loading state and retry logic rather than relying on a bare alert.

2. VFS Virtual File System

FetchFileToVFS reads an Excel file from the static assets directory into the virtual file system inside WASM.

Limitation: This example reads a static Excel file bundled with the project. If users need to upload arbitrary Excel files, read the File object and write it into the VFS instead of fetching it from PUBLIC_URL.

3. Iterating Over and Saving Pictures

The sheet.Pictures collection contains all floating pictures on the worksheet. pic.Picture.Save() only writes the image to the WASM virtual file system; it does not automatically download the file to the local machine. This is a common pitfall.

This example always outputs PNG. The library generally supports JPG as well—change the format as needed.

4. Blob Downloads and Resource Cleanup

  • FS.readFile returns the Uint8Array binary data for the file in the VFS.
  • Create a temporary URL with URL.createObjectURL, and call revokeObjectURL after the download to free memory.
  • workbook.Dispose(): WASM objects are not automatically reclaimed by JavaScript’s garbage collector, so you must release them manually. This is especially important when parsing files repeatedly in batches.

Solution Comparison

Approach Pros Cons
Backend parses Excel and returns images Low frontend load; best compatibility Requires a server endpoint; files must be uploaded; network overhead
Frontend WASM parsing (this article’s approach) No file upload; local, offline processing; privacy-friendly Large WASM bundle; higher browser memory usage

Conclusion

With the WASM capabilities of Spire.XLS for JavaScript, you can extract embedded Excel images entirely in the frontend without uploading files to a backend. This approach works well for internal tools, offline admin backends, and similar scenarios.

The example code is a minimal usable version. Before shipping to production, consider adding file upload interaction, error handling, loading states, and batch ZIP download support for multiple images.

Top comments (0)