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:
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>
<html>
<head>
<title>SpreadJS ExcelIO</title>
<script src="./node_modules/jquery/dist/jquery.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2014-11-29/FileSaver.min.js"></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>
</head>
<body>
<div id="ss" style="height:600px; width :100%; "></div>
</body>
</html>
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"));
});
</script>
</head>
<body>
<div id="ss" style="height:600px ; width :100%; "></div>
</body>
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="http://www.testwebsite.com/files/TestExcel.xlsx" 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();
oReq.open('get', excelUrl, true);
oReq.responseType = 'blob';
oReq.onload = function () {
var blob = oReq.response;
excelIO.open(blob, LoadSpread, function (message) {
console.log(message);
});
};
oReq.send(null);
}
function LoadSpread(json) {
jsonData = json;
workbook.fromJSON(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.
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:
document.getElementById("addRevenue").onclick = function () {
var sheet = workbook.getActiveSheet();
sheet.addRows(newRowIndex, 1);
sheet.copyTo(10, 1, newRowIndex, 1, 1, 29, GC.Spread.Sheets.CopyToOptions.style);
}
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);
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:
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:
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:
workbook.suspendPaint();
workbook.suspendCalcService();
//...
workbook.resumeCalcService();
workbook.resumePaint();
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.
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());
excelIO.save(json, function (blob) {
saveAs(blob, fileName);
}, function (e) {
if (e.errorCode === 1) {
alert(e.errorMessage);
}
});
}
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 () {
ExportFile();
}
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="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2014-11-29/FileSaver.min.js"></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.
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!