Quick Start Guide | |
---|---|
Tutorial Concept | Learn how to import, modify, and export Excel (.xlsx) files in React applications. |
What You Will Need |
React v18 |
Controls Referenced |
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!
How to Import and Export Excel (.XLSX) Files in React Applications
- Create a React Spreadsheet Application
- Add Excel Import Code
- Update the Imported XLSX
- Add Excel Export Code
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-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:
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 FileType 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:
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.
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 --save
npm 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.
Learn More About React Spreadsheet Components
This article only scratches the surface of the full capabilities of SpreadJS, the React spreadsheet component. Review the documentation to see some of the many available features, and check out our online 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:
In another article series, we demonstrate how to import/export Excel (.xlsx) spreadsheets in other frameworks: