How to Import and Export Excel XLSX Using JavaScript

JavaScript is a versatile platform that allows easy customization of client-side scripting tools. In some applications, it's helpful to have some sort of spreadsheet interface that is easy to code and maintain. The SpreadJS client-side JavaScript spreadsheet component is perfect for this.

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

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

  1. Set Up the JavaScript Spreadsheet Project
  2. Add Excel Import Code
  3. Add Data to the Imported Excel File
  4. Add a Sparkline
  5. Add Excel Export Code


Set Up the JavaScript Spreadsheet Project

To start, we can use the SpreadJS files hosted on NPM. To do this, we can install using a command line argument. Open a command prompt and navigate to the location of your application. There, you can install the required files with one command.

In this case, we need the base Spread-Sheets library, Spread-ExcelIO, and jQuery:

npm i @grapecity/spread-sheets @grapecity/spread-excelio jquery

SpreadJS isn’t dependent on jQuery, but in this case, we use it for the easy cross-origin-request support, which we will review later.

Once those are installed, we can add references to those script and CSS files in our code:

<!DOCTYPE html>  
    <title>SpreadJS ExcelIO</title>
    <script src="./node_modules/jquery/dist/jquery.min.js" type="text/javascript"></script>
    <script src=""></script>

    <link href="./node_modules/@grapecity/spread-sheets/styles/gc.spread.sheets.excel2013white.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript" src="./node_modules/@grapecity/spread-sheets/dist/gc.spread.sheets.all.min.js"></script>
    <script type="text/javascript" src="./node_modules/@grapecity/spread-excelio/dist/gc.spread.excelio.min.js"></script>

    <div id="ss" style="height:600px; width :100%; "></div>  


We will also need the FileSaver library, which we have imported in addition to the SpreadJS and jQuery files.

Then we can add a script to the page that initializes the Spread.Sheets component and a div element to contain it (since the SpreadJS spreadsheet component utilizes a canvas, this is necessary to initialize the component):

    <script type="text/javascript">  
        $(document).ready(function () {  
            var workbook = new GC.Spread.Sheets.Workbook(document.getElementById("ss"));  
    <div id="ss" style="height:600px ; width :100%; "></div>  

Add Excel Import Code

We need to create an instance of the client-side ExcelIO component that we can use to open the file:

var excelIO = new GC.Spread.Excel.IO();  

Then we need to add a function to import a file. In this example, we import a local file, but you can do the same thing with a file on a server. You need to reference the location if importing a file from a server. The following is an example of an input element where the user can enter the location of the file:

<input type="text" id="importUrl" value="" style="width:300px" />

Once you have that, you can directly access that value in script code:

var excelUrl = $("#importUrl").val();  

The following code for the import function uses a local file for the "excelUrl" variable:

function ImportFile() {  
    var excelUrl = "./test.xlsx";  

    var oReq = new XMLHttpRequest();'get', excelUrl, true);  
    oReq.responseType = 'blob';  
    oReq.onload = function () {  
        var blob = oReq.response; , LoadSpread, function (message) {  
function LoadSpread(json) {  
    jsonData = json;  

    workbook.setActiveSheet("Revenues (Sales)");  

Whether you're referencing a file on a server or locally, you'll need to add the following to your script inside the $(document).ready function:

$(document).ready(function () {  
    $.support.cors = true;  
    workbook = new GC.Spread.Sheets.Workbook(document.getElementById("ss"));  

In this case, we need to enable Cross-Origin-Request-Support because we are potentially loading a file from a URL. Hence the $.support.cors = true; line, or else attempting to load it will result in a CORS error.

Add Data to the Imported Excel File

We import a local file using the “Profit loss statement” Excel template for this tutorial.

Now we can use Spread.Sheets script to add another revenue line into this file. Let’s add a button to the page that will do just that:

<button id="addRevenue">Add Revenue</button>  

We can write a function for the click event handler for that button to add a row and copy the style from the previous row in preparation for adding some data. To copy the style, we will need to use the copyTo function and pass in:

  • the origin and destination row and column indices
  • row and column count
  • the CopyToOptions value for style
document.getElementById("addRevenue").onclick = function () {  
    var sheet = workbook.getActiveSheet();  
    sheet.addRows(newRowIndex, 1);  
    sheet.copyTo(10, 1, newRowIndex, 1, 1, 29,;  

The following script code for adding data and a Sparkline will be contained within this button click event handler. For most of the data, we can use the setValue function. This allows us to set a value in a sheet in Spread by passing in a row index, column index, and value:

sheet.setValue(newRowIndex, 1, "Revenue 8");  

for (var c = 3; c < 15; c++) {  
    sheet.setValue(newRowIndex, c, Math.floor(Math.random() * 200) + 10);  

Set a SUM formula in column P to match the other rows and set a percentage for column Q:

sheet.setFormula(newRowIndex, 15, "=SUM([@[Jan]:[Dec]])")  
sheet.setValue(newRowIndex, 16, 0.15);  

Lastly, we can copy the formulas from the previous rows to the new row for columns R through AD using the copyTo function again, this time using CopyToOptions.formula:

sheet.copyTo(10, 17, newRowIndex, 17, 1, 13, GC.Spread.Sheets.CopyToOptions.formula);  

Add a Sparkline

Now we can add a sparkline to match the other rows of data. To do this, we need to provide a range of cells to get the data from and some settings for the sparkline. In this case, we can specify:

  • the range of cells, we just added data to
  • settings to make the sparkline look like the other sparklines in the same column
var data = new GC.Spread.Sheets.Range(11, 3, 1, 12);  
var setting = new GC.Spread.Sheets.Sparklines.SparklineSetting();  
setting.options.seriesColor = "Text 2";  
setting.options.lineWeight = 1;  
setting.options.showLow = true;  
setting.options.showHigh = true;  
setting.options.lowMarkerColor = "Text 2";  
setting.options.highMarkerColor = "Text 1";  

After that, we call the setSparkline method and specify:

  • a location for the sparkline
  • the location of the data
  • the orientation of the sparkline
  • the type of sparkline
  • the settings we created
sheet.setSparkline(11, 2, data, GC.Spread.Sheets.Sparklines.DataOrientation.horizontal, GC.Spread.Sheets.Sparklines.SparklineType.line, setting);  

If you were to try running the code now, it might seem a little slow because the workbook is repainting every time data is changed and styles are added. To drastically speed it up and increase performance, Spread.Sheets provide the ability to suspend painting and the calculation service. Let’s add the code to suspend both before adding a row and its data and then resume both after:


Once we add that code, we can open the page in a web browser and see the Excel file load into Spread.Sheets with an added revenue row. Important: Keep in mind that Chrome doesn’t allow you to open local files for security purposes, so you need to use a web browser like Firefox to run this code successfully. Alternatively, loading a file from a website URL should open fine in any browser.

Add Excel Export Code

Finally, we can add a button to export the file with the added row. To do this, we can use the client-side ExcelIO code built into Spread.Sheets:

function ExportFile() {  
    var fileName = $("#exportFileName").val();  
    if (fileName.substr(-5, 5) !== '.xlsx') {  
        fileName += '.xlsx';  
    var json = JSON.stringify(workbook.toJSON());, function (blob) {  
        saveAs(blob, fileName);  
    }, function (e) {  
        if (e.errorCode === 1) {  

That code gets the export file name from an exportFileName input element. We can define it and let users name the file like so:

<input type="text" id="exportFileName" placeholder="Export file name" value="export.xlsx" />  

Then we can add a button that calls this function:

<button id="export">Export File</button>  
document.getElementById("export").onclick = function () {  

Once you add a revenue row, you can export the file using the Export File button. Make sure to add the FileSaver external library to allow users to save the file where they want:

<script src=""></script>  

When the file is successfully exported, you can open it in Excel and see that the file looks like it did when it was imported, except there is now an extra revenue line that we added.

This is just one example of how you can use SpreadJS JavaScript spreadsheets to add data to your Excel files and then export them back to Excel with simple JavaScript code.

Download the sample here.

In another article series, we demonstrate how to import/export Excel spreadsheets in other Javascript frameworks:

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


comments powered by Disqus