How to Import and Export Excel XLSX Using React
Tags: webdev, devops, tutorial, react
Published: 2022-06-24 21:05:00

---
canonical_url: https://developer.mescius.com/blogs/how-to-import-export-excel-xlsx-using-react
description: Learn how to import and export Excel XLSX files using React. See more from SpreadJS today.
---

**What You Will Need**
- React v18
- NPM Packages:
- [@mescius/spread-sheets]
(https://www.npmjs.com/package/@mescius/spread-sheets)
- [@mescius/spread-sheets-io]
(https://www.npmjs.com/package/@mescius/spread-sheets-io)
- [@mescius/spread-sheets-charts]
(https://www.npmjs.com/package/@mescius/spread-sheets-charts)
- [@mescius/spread-sheets-shapes]
(https://www.npmjs.com/package/@mescius/spread-sheets-shapes)
- [file-saver]
(https://www.npmjs.com/package/file-saver)

**Controls Referenced**
- [SpreadJS - React Spreadsheet Component](https://developer.mescius.com/spreadjs/react-spreadsheet-components)
- [Documentation](https://developer.mescius.com/spreadjs/docs/overview)
- [Demos](https://developer.mescius.com/spreadjs/demos/features/spreadjs-file-format/overview/react)

**Tutorial Concept**
Discover how easy it is to work with Excel XLSX files in React apps by using a user-friendly React Spreadsheet UI Component and API library for importing, modifying, and exporting data.

---

Many businesses utilize spreadsheets, particularly Microsoft Excel, to aid in managing their operations. Whether these are internal spreadsheets or ones provided by clients, it is essential that these files can be accessed and/or managed within React applications.

This article outlines how to seamlessly import Excel files into a user-friendly spreadsheet interface, make modifications programmatically or enable user edits, and export the updated data back into an Excel file with the widely-used [<span>SpreadJS client-side React spreadsheet component</span>](https://developer.mescius.com/spreadjs/react-spreadsheet-components "https://developer.mescius.com/spreadjs/react-spreadsheet-components").

**In this blog, we will cover how to import/export to Excel in React following these steps:**

1.  [<span>Create a React Spreadsheet Application</span>](#create)
2.  [<span>Add Excel Import Code</span>](#Import)
3.  [<span>Update the Imported XLSX</span>](#Update)
4.  [<span>Add Excel Export Code</span>](#Export)

![Import/Export Excel/XLSX React](//cdn.mescius.io/umb/media/zftllqxr/sjs-io-react-1.png?rmode=max&width=754&height=377)

[**<span>Download the sample application to follow along with the blog.</span>**](https://mcspubcdn.blob.core.windows.net/assets/developer/blogs/spread/20240411-Import-Export-Excel-React-SJS/sjs-react-io.zip "https://mcspubcdn.blob.core.windows.net/assets/developer/blogs/spread/20240411-Import-Export-Excel-React-SJS/sjs-react-io.zip")

## <a id="create"></a>Create a React Spreadsheet Application

Create a React Project by opening the Command Prompt window and typing the following commands:

```
    npx create-react-app sjs-react-io
    cd sjs-react-io
    npm start
```

Next, install the necessary SpreadJS modules in your project using the following command:

```
    npm install @mescius/spread-sheets @mescius/spread-sheets-react @mescius/spread-sheets-io @mescius/spread-sheets-charts @mescius/spread-sheets-shapes
```

Import the SpreadJS CSS in your apps **index.js** file using the following code:

```
    import '@mescius/spread-sheets/styles/gc.spread.sheets.excel2013white.css';
```

In the **App.js** file, declare the imports of the MESCIUS components. These Imports will enable access to the React Spreadsheets object of the SpreadJS library and support for charts, shapes, and import/expo in the spreadsheet instance.

```
    import React, { Component } from "react";
    import { SpreadSheets } from "@mescius/spread-sheets-react";
    import * as GC from "@mescius/spread-sheets";
    import "@mescius/spread-sheets-charts";
    import "@mescius/spread-sheets-shapes";
    import "@mescius/spread-sheets-io";
```

Inside the render() function of the App component, add the React **Spreadsheets** component to display the spreadsheet instance. Additionally, add an input field and buttons for file-handling operations. Define methods for handling file operations such as saving, opening, changing the imported file, and adding data. Placeholder logic will be added for now:

```
    class App extends Component {
      constructor(props) {
        super(props);
        this.hostStyle = {
          width: "950px",
          height: "600px",
        };
        this.spread = null;
      }
      render() {
        return (
          <div style={{ display: "flex" }}>
            <div style={{ width: "950px", height: "600px" }}>
              <SpreadSheets
                workbookInitialized={(spread) => this.initSpread(spread)}
                hostStyle={this.hostStyle}
              ></SpreadSheets>
            </div>
            <div style={{ width: "200px", padding: "20px", background: "#ddd" }}>
              <p>Open Excel Files (.xlsx)</p>
              <input type="file" onChange={this.handleFileChange} />
              <button onClick={this.handleOpenExcel}>Open Excel</button>
              <p>Add Data</p>
              <button onClick={this.handleAddData}>Add Customer</button>
              <p>Save File</p>
              <button onClick={this.handleSaveExcel}>Save Excel</button>
            </div>
          </div>
        );
      }
      initSpread(spread) {
        this.spread = spread;
        this.spread.setSheetCount(2);
        console.log(this.spread);
      }
      handleSaveExcel = () => {
        // Logic to save to Excel
      };
      handleOpenExcel = () => {
        // Logic to import an Excel file
      };
      handleFileChange = (e) => {
        // Logic to change the imported file
      };
      handleAddData = () => {
        // Logic to add data
      };
    }
    export default App;
```

Save all the files, and run the React app:

```
    npm start
```

You have now created a React Spreadsheet app:

![Import/Export Excel/XLSX React](//cdn.mescius.io/umb/media/05ddg4v2/3-20240409-155728.png?rmode=max&width=724&height=362)

<div class="MsoNormal">

* * *

</div>

## <a id="Import"></a>Add Excel Import Code to a React App

In the constructor, initialize the _state_ with _selectedFile_ set to null, indicating that no file is selected initially. The **handleFileChange** function correctly captures the selected Excel file when it's changed and updates the component's state with the selected file.

```
    constructor(props) {
        super(props);
        this.hostStyle = {
          width: "950px",
          height: "600px",
        };
        this.spread = null;
        this.state = {
          selectedFile: null,
        };
        this.currentCustomerIndex = 0;
      }
    ...
    handleFileChange = (e) => {
        this.setState({
          selectedFile: e.target.files[0],
        });
      };
```

The **handleOpenExcel** function is triggered when the user clicks the "Open Excel" button. It first checks if a file is selected. If not, it returns early. If a file is selected, it constructs import options specifying the [**<span>FileType</span> **as _excel_](https://developer.mescius.com/spreadjs/api/enums/GC.Spread.Sheets.FileType#enumeration-filetype "https://developer.mescius.com/spreadjs/api/enums/GC.Spread.Sheets.FileType#enumeration-filetype")_._ Then, it calls the [**import** method](https://developer.mescius.com/spreadjs/api/v16/classes/GC.Spread.Sheets.Workbook#import "https://developer.mescius.com/spreadjs/api/v16/classes/GC.Spread.Sheets.Workbook#import") of the SpreadJS instance (this.spread) with the selected file and import options.

```
    handleOpenExcel = () => {
        const file = this.state.selectedFile;
        if (!file) {
          return;
        }
        // Specify the file type to ensure proper import
        const options = {
          fileType: GC.Spread.Sheets.FileType.excel,
        };
        this.spread.import(
          file,
          () => {
            console.log("Import successful");
          },
          (e) => {
            console.error("Error during import:", e);
          },
          options
        );
      };
```

Alternatively, you can read an Excel file from a URL on a server. [<span>See our blog here</span>](/blogs/how-to-read-excel-xlsx-files-from-a-url-using-javascript "/blogs/how-to-read-excel-xlsx-files-from-a-url-using-javascript").

Run the app and notice an Excel (.xlsx) file can now be imported and viewed in the React spreadsheet component like so:

![Import/Export Excel/XLSX React](//cdn.mescius.io/umb/media/zsoiagmo/import-excel-sjs-react.gif?rmode=max&width=744&height=372)

<div class="MsoNormal">

* * *

</div>

## <a id="Update"></a>Update XLSX File Programmatically in a React app

After successfully importing an Excel file into SpreadJS, users can easily interact with the spreadsheet data. Alternatively, you may need to programmatically modify the data within the spreadsheet. This can be accomplished by utilizing SpreadJS’s comprehensive API.

This section introduces the function **handleAddData**, which adds new customer data to the imported .xlsx file data when clicking a button. First, we need to create a **currentCustomerIndex** variable, this will be used as a counter related to the sample data:

```
     handleAddData = () => {
        // Create new row and copy styles
        var newRowIndex = 34;
        var sheet = this.spread.getActiveSheet();
        sheet.addRows(newRowIndex, 1);
        sheet.copyTo(
          32,
          1,
          newRowIndex,
          1,
          1,
          11,
          GC.Spread.Sheets.CopyToOptions.style
        );
        // Define sample customer data
        var customerDataArrays = [
          ["Jessica Moth", 5000, 2000, 3000, 1300, 999, 100],
          ["John Doe", 6000, 2500, 3500, 1400, 1000, 20],
          ["Alice Smith", 7000, 3000, 4000, 1500, 1100, 0],
        ];
        // Get the current customer data array
        var currentCustomerData = customerDataArrays[this.currentCustomerIndex];
        // Add new data to the new row
        sheet.setArray(newRowIndex, 5, [currentCustomerData]);
        newRowIndex++;
        // Increment the index for the next button click
        this.currentCustomerIndex =
          (this.currentCustomerIndex + 1) % customerDataArrays.length;
      };
```

Notice that new customer data is added to the statement when the button is clicked, and the formulas within the worksheet update accordingly.

![Import/Export Excel/XLSX React](//cdn.mescius.io/umb/media/yksli02u/modify-excel-file-in-react-app.gif?rmode=max&width=752&height=376)

<div class="MsoNormal">

* * *

</div>

## <a name="Export"></a>Add Excel Export Code to a React App

With the [**<span>export</span>**](https://developer.mescius.com/spreadjs/api/v16/classes/GC.Spread.Sheets.Workbook#export "https://developer.mescius.com/spreadjs/api/v16/classes/GC.Spread.Sheets.Workbook#export") [method](https://developer.mescius.com/spreadjs/api/v17/classes/GC.Spread.Sheets.Workbook#export "https://developer.mescius.com/spreadjs/api/v17/classes/GC.Spread.Sheets.Workbook#export") included with SpreadJS and the [file-saver npm package](https://www.npmjs.com/package/file-saver "https://www.npmjs.com/package/file-saver"), React app developers can effortlessly export a spreadsheet state as an Excel file. First, install the file-saver npm package.

```
    npm install file-saver --save
    npm i --save-dev @types/file-saver
```

Import the [_<span>file-saver</span>_ package](https://www.npmjs.com/package/file-saver "https://www.npmjs.com/package/file-saver") to the **App.js** file.

```
    import React, { Component } from "react";
    import { SpreadSheets } from "@mescius/spread-sheets-react";
    import * as GC from "@mescius/spread-sheets";
    import "@mescius/spread-sheets-charts";
    import "@mescius/spread-sheets-shapes";
    import "@mescius/spread-sheets-io";
    import { saveAs } from "file-saver";
    ...
```

Update the **handleSaveExcel** function by specifying the exported XLSX file name, “Excel_Export.xlsx”, then invoke the SpreadJS [**<span>export</span>** method](https://developer.mescius.com/spreadjs/api/v16/classes/GC.Spread.Sheets.Workbook#export "https://developer.mescius.com/spreadjs/api/v16/classes/GC.Spread.Sheets.Workbook#export"). This method exports the React spreadsheet state into a Blob. Within the export method, invoke the file-saver's **saveAs** method to save the exported spreadsheet Blob as an actual Excel file on the client-side.

```
      handleSaveExcel = () => {
        var fileName = "Excel_Export.xlsx";
        this.spread.export(
          function (blob) {
            // save blob to a file
            saveAs(blob, fileName);
          },
          function (e) {
            console.log(e);
          },
          {
            fileType: GC.Spread.Sheets.FileType.excel,
          }
        );
      };
```

You've successfully added Excel export functionality to the React spreadsheet application with these steps.

![Import/Export Excel/XLSX React](//cdn.mescius.io/umb/media/32npqlqm/export-excel-from-react.gif?rmode=max&width=718&height=359)

Don’t forget to [<span>download this blog's sample application</span>](https://mcspubcdn.blob.core.windows.net/assets/developer/blogs/spread/20240411-Import-Export-Excel-React-SJS/sjs-react-io.zip "https://mcspubcdn.blob.core.windows.net/assets/developer/blogs/spread/20240411-Import-Export-Excel-React-SJS/sjs-react-io.zip") to try importing/exporting your own Excel files in a React application.

<div class="MsoNormal">

* * *

</div>

## **Learn More About React Spreadsheet Components**

This article only scratches the surface of the full capabilities of **SpreadJS**, the [<span>React spreadsheet component</span>](https://developer.mescius.com/spreadjs/react-spreadsheet-components "https://developer.mescius.com/spreadjs/react-spreadsheet-components"). Review the [documentation](https://developer.mescius.com/spreadjs/docs/overview "https://developer.mescius.com/spreadjs/docs/overview") to see some of the many available features, and check out our [online demos](https://developer.mescius.com/spreadjs/demos "https://developer.mescius.com/spreadjs/demos") to see the features in action and interact with the sample code. Integrating a spreadsheet component into your applications allows you to customize your users' experience and provide them with familiar spreadsheet functionality without referring them to an external program.

Check out our video to learn more:
{% embed https://youtu.be/jACaSv6JVAc %}