How to Import and Export Excel XLSX Using React | SpreadJS (2024)

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 SpreadJS client-side React spreadsheet component.

Add React spreadsheets into your enterprise web apps. Download SpreadJS Now!

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

  1. Create a React Spreadsheet Application
  2. Add Excel Import Code
  3. Update the Imported XLSX
  4. Add Excel Export Code

How to Import and Export Excel XLSX Using React | SpreadJS (1)

Download the sample application to follow along with the blog.

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-iocd sjs-react-ionpm 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:

How to Import and Export Excel XLSX Using React | SpreadJS (2)

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 theFileType as excel. Then, it calls the import method 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. See our blog here.

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

How to Import and Export Excel XLSX Using React | SpreadJS (3)

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.

How to Import and Export Excel XLSX Using React | SpreadJS (4)

Add Excel Export Code to a React App

With the export method included with SpreadJS and the file-saver npm package, React app developers can effortlessly export a spreadsheet state as an Excel file. First, install the file-saver npm package.

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

Import the file-saver package 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 export method. 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.

How to Import and Export Excel XLSX Using React | SpreadJS (5)

Don’t forget to download this blog's sample application to try importing/exporting your own Excel files in a React application.

Learn More About React Spreadsheet Components

This article only scratches the surface of the full capabilities of SpreadJS, the React spreadsheet component. Review thedocumentationto see some of the many available features, and check out ouronline 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.

Ready to add React spreadsheets into your enterprise web apps? Download SpreadJS Now!

Check out our video to learn more:

How to Import and Export Excel XLSX Using React | SpreadJS (2024)
Top Articles
Is Costco Membership Free with the Citi Credit Card?
How To Create A Quick Reference Guide | EDC
Davita Internet
Trabestis En Beaumont
Stadium Seats Near Me
Arkansas Gazette Sudoku
Mama's Kitchen Waynesboro Tennessee
Hertz Car Rental Partnership | Uber
Obituary (Binghamton Press & Sun-Bulletin): Tully Area Historical Society
Bluegabe Girlfriend
Tight Tiny Teen Scouts 5
Tcu Jaggaer
Turbocharged Cars
David Turner Evangelist Net Worth
How To Cut Eelgrass Grounded
5 high school volleyball stars of the week: Sept. 17 edition
Download Center | Habasit
Everything We Know About Gladiator 2
The Exorcist: Believer (2023) Showtimes
Huntersville Town Billboards
Spn 520211
St Clair County Mi Mugshots
At&T Outage Today 2022 Map
Wiseloan Login
Elite Dangerous How To Scan Nav Beacon
Weathervane Broken Monorail
Cowboy Pozisyon
Craftsman Yt3000 Oil Capacity
Otis Inmate Locator
Current Time In Maryland
Little Caesars Saul Kleinfeld
Clearvue Eye Care Nyc
Makemkv Key April 2023
Black Adam Showtimes Near Amc Deptford 8
Elgin Il Building Department
Mcgiftcardmall.con
Wisconsin Women's Volleyball Team Leaked Pictures
Frommer's Philadelphia &amp; the Amish Country (2007) (Frommer's Complete) - PDF Free Download
11301 Lakeline Blvd Parkline Plaza Ctr Ste 150
Bcy Testing Solution Columbia Sc
Entry of the Globbots - 20th Century Electro​-​Synthesis, Avant Garde & Experimental Music 02;31,​07 - Volume II, by Various
Unitedhealthcare Community Plan Eye Doctors
Conan Exiles Colored Crystal
Black Adam Showtimes Near Kerasotes Showplace 14
Nfhs Network On Direct Tv
Unbiased Thrive Cat Food Review In 2024 - Cats.com
Ranking 134 college football teams after Week 1, from Georgia to Temple
Latest Posts
Article information

Author: Merrill Bechtelar CPA

Last Updated:

Views: 5964

Rating: 5 / 5 (70 voted)

Reviews: 85% of readers found this page helpful

Author information

Name: Merrill Bechtelar CPA

Birthday: 1996-05-19

Address: Apt. 114 873 White Lodge, Libbyfurt, CA 93006

Phone: +5983010455207

Job: Legacy Representative

Hobby: Blacksmithing, Urban exploration, Sudoku, Slacklining, Creative writing, Community, Letterboxing

Introduction: My name is Merrill Bechtelar CPA, I am a clean, agreeable, glorious, magnificent, witty, enchanting, comfortable person who loves writing and wants to share my knowledge and understanding with you.