Skip to main content Skip to footer

How to Add a React Excel XLSX Viewer to Your Web Application

SpreadJS, GrapeCity’s JavaScript spreadsheet, is an amazing client-side control that allows you to load, edit, and save even your most complicated .XLSX spreadsheet files within different frameworks. In this blog, we will use SpreadJS and React to show how you can use SpreadJS to add an XLSX Viewer to your application.

React Excel XLSX Viewer

Download the sample to follow along.

Ready to Get Started? Download SpreadJS Today!

Creating a New Project

We can start by creating a new project using the terminal:

npm init react-app spreadjs-react-app
cd spreadjs-react-app

We can also add SpreadJS to it using NPM:

npm install @grapecity/spread-sheets @grapecity/spread-sheets-react @grapecity/spread-excelio

We should also install the FileSaver library:

npm install file-saver

We can now add SpreadJS code to this application.

Add SpreadJS Code

We can start by importing the required libraries into our component in the src>App.js file:

import './App.css';
import React, { Component } from 'react';
import * as GC from '@grapecity/spread-sheets';
import { SpreadSheets, Worksheet, Column } from '@grapecity/spread-sheets-react';
import { IO } from "@grapecity/spread-excelio";
import '@grapecity/spread-sheets/styles/gc.spread.sheets.excel2013white.css';
import saveAs from 'file-saver';

Now that we have everything we need imported, we can start creating the component code, beginning with the constructor that we’ll define variables in, as well as initializing the SpreadJS instance:

class App extends Component {
  constructor(props) {
    super(props);
    this.spread = null;
    this.spreadBackColor = 'aliceblue';
    this.sheetName = 'Goods List';
    this.hostStyle = {
        width: '100%',
        height: '600px',
        border: '1px solid darkgray'
    };
    this.data = [
      {
        Name: "Apple",
        Category: "Fruit",
        Price: 1,
        "Shopping Place": "Wal-Mart",
      },
      {
        Name: "Potato",
        Category: "Fruit",
        Price: 2.01,
        "Shopping Place": "Other",
      },
      {
        Name: "Tomato",
        Category: "Vegetable",
        Price: 3.21,
        "Shopping Place": "Other",
      },
      {
        Name: "Sandwich",
        Category: "Food",
        Price: 2,
        "Shopping Place": "Wal-Mart",
      },
      {
        Name: "Hamburger",
        Category: "Food",
        Price: 2,
        "Shopping Place": "Wal-Mart",
      },
      {
        Name: "Grape",
        Category: "Fruit",
        Price: 4,
        "Shopping Place": "Sun Store",
      },
    ];

    this.columnWidth = 100;
    this.importExcelFile = null;
    this.exportFileName = "export.xlsx";
    this.password = "";
  }

  initSpread(spread) {
    this.spread = spread;
    spread.options.calcOnDemand = true;
  }
}

We also need to add a render function for what we want to be displayed on the webpage:

render() {
  return (
    <div className="App">
      <div class="sample-spreadsheets">
        <SpreadSheets workbookInitialized={spread => this.initSpread(spread)}  hostStyle={this.hostStyle}>
          <Worksheet name="Goods List" dataSource={this.data}>
            <Column dataField='Name' width={300}></Column>
            <Column dataField='Category' width={100}></Column>
            <Column dataField='Price' width={100} formatter="$#.00"></Column>
            <Column dataField='Shopping Place' width={100}></Column>
          </Worksheet>
        </SpreadSheets>
      </div>
    </div>
  )
}

To run the app, use npm start in a command line, and this should open up in a web browser:

React Excel XLSX Viewer

Add Excel Import/Export Code

The SpreadJS instance is now set up, and we can start adding ExcelIO code. This can be done in the same App.js file as before. We can first add some buttons for the UI right under our SpreadJS element:

<div className="options-container">
  <div className="option-row">
    <div className="inputContainer">
      <input type="file" id="fileDemo" className="input" accept=".xlsx" onChange={e=>this.changeFileDemo(e)}/>
      <input type="button" id="loadExcel" defaultValue="import" className="button" onClick={e=>this.loadExcel(e)}/>
    </div>
    <div className="inputContainer">
      <input id="exportFileName" defaultValue="export.xlsx" className="input" onChange={e=>this.changeExportFileName(e)}/>
      <input type="button" id="saveExcel" defaultValue="export" className="button" onClick={e=>this.saveExcel(e)}/>
    </div>
  </div>
  <div className="option-row">
    <div className="group">
        <label>Password:
          <input type="password" id="password" onChange={e=>this.changePassword(e)}/>
        </label>
    </div>
  </div>
</div>

Now we can add the functions for these buttons:

changeFileDemo(e) {
  this.importExcelFile = e.target.files[0];
}

changePassword(e) {
  this.password = e.target.value;
}

changeExportFileName(e) {
  this.exportFileName = e.target.value;
}

We can now add code for loading an Excel file into SpreadJS, and in the case of this sample, we can utilize a password when opening:

loadExcel(e) {
  let spread = this.spread;
  let excelIo = new IO();
  let excelFile = this.importExcelFile;
  let password = this.password;

  excelIo.open(excelFile, function (json) {
    let workbookObj = json;
    spread.fromJSON(workbookObj);
  }, function (e) {
    alert(e.errorMessage);
  }, { password: password });
}

We can also save Excel files with an optional password, and in this case, we are also going to need the includeBindingSource option for data-bound workbooks:

saveExcel(e) {
  let spread = this.spread;
  let excelIo = new IO();

  let fileName = this.exportFileName;
  let password = this.password;
  if (fileName.substr(-5, 5) !== '.xlsx') {
      fileName += '.xlsx';
  }

  let json = spread.toJSON({includeBindingSource: true});

  excelIo.save(json, function (blob) {
    saveAs(blob, fileName);
  }, function (e) {
    console.log(e);
  }, { password: password });
}

React Excel XLSX Viewer

That is all that is needed to create an Excel spreadsheet viewer using SpreadJS in a React application!

To try this out for yourself, download the sample and a trial of SpreadJS today!

 

Tags:

comments powered by Disqus