How to Import and Export CSV Files Using JavaScript

MESCIUS inc.
MESCIUS inc.
Published in
5 min readJun 7, 2024

What You Will Need
• SpreadJS
• NPM
• Visual Studio Code

Controls Referenced
SpreadJS

Tutorial Concept
Import/Export CSV JavaScript — Add the functionality to import and export CSV files in your web application using SpreadJS features.

In the ever-evolving landscape of web development, JavaScript reigns supreme as a versatile and powerful language. As JavaScript developers, we often find ourselves tasked with handling data in various formats, and one common requirement is working with CSV files. Whether you need to import data from external sources, perform data analysis, or simply present information in a structured tabular format, knowing how to import, modify data, and export CSV files can be a game-changer. In this blog, we will explore the ins and outs of CSV file manipulation in a JavaScript spreadsheet solution. We’ll take it a step further by introducing you to SpreadJS, a robust JavaScript spreadsheet component to load CSV data, visualize it within a JS spreadsheet, and export it to a CSV file. So, let’s dive in and unlock the potential of seamless CSV file handling in the world of JavaScript development.

Follow the steps below to import and export CSV files in a JavaScript spreadsheet application:

  1. Add SpreadJS to a JavaScript App
  2. Add HTML Buttons for Import and Export
  3. Import CSV Data to JS App Using SpreadJS’s setCsv Method
  4. Export JS Data to a CSV File Using SpreadJS’s getCsv Method

To follow along with this tutorial, you can download the sample.

Add SpreadJS to a JavaScript App

To get started with this example, create an app, reference SpreadJS’s files, and initialize the JavaScript spreadsheet component. In this case, we can use NPM to install the required SpreadJS files:

npm install @mescius/spread-sheets

Then, we need to reference those files in the code:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<!-- Add the SpreadJS Script file-->
<script
src="./node_modules/@mescius/spread-sheets/dist/gc.spread.sheets.all.min.js"
type="text/javascript"></script>
<!-- Add the SpreadJS CSS File-->
<link rel="stylesheet" type="text/css"
href="./node_modules/@mescius/spread-sheets/styles/gc.spread.sheets.excel2013white.css">
<style>
.spread-container {
height: 550px;
}
</style>
</head>
<body>
<h1>SpreadJS - Import and Export CSV Data</h1>
<div class="sample-container">
<!-- Create SpreadJS's target DOM element, HTML DIV with id ss-->
<div id="ss" class="spread-container"></div>
</div>
</body>
<script>
var spread;
// Initialize SpreadJS in spread-container by div's id "ss"
window.onload = function ()
{
spread = new GC.Spread.Sheets.Workbook("ss", { sheetCount: 1 });
};
</script>
</html>

This is how SpreadJS will appear:

Add HTML Buttons for Import and Export

Next, add two buttons and a file selector input to the webpage:

<body>
<h1>SpreadJS - Import and Export CSV Data</h1>
<!-- Add file selector Import/Export buttons -->
<input id="selectedFile" type="file" name="files[]" accept=".csv" />
<button onclick="importCSV()">Import CSV</button>
<button onclick="exportCSV()">Export CSV</button>

<div class="sample-container">
<!-- Create SpreadJS's target DOM element, HTML DIV with id ss-->
<div id="ss" class="spread-container"></div>
</div>
</body>

Then, create onclick events for both of the buttons:

<script>
var spread;
// Initialize SpreadJS in spread-container by div's id "ss"
window.onload = function ()
{
spread = new GC.Spread.Sheets.Workbook("ss", { sheetCount: 1 });
};
// Import/Export button onclick functions
function importCSV() {
console.log("import button");
}
function exportCSV() {
console.log("export button");
}
</script>

After implementing this code, we can see the file selector and the button onclick functions are working properly:

Import CSV Data to JS App Using SpreadJS’s setCsv Method

To import CSV data, invoke SpreadJS’s setCsv method within the importCSV function. The setCsv method has a rowDelimiter and columnDelimiter as the fourth and fifth parameters, respectively. These can be changed to different symbols; for example, changing the columnDelimiter from “,” to “\t”, which will support TSV files as well. In the case of this example, we are just going to use commas. We need to retrieve the file from the input, read it as text, and then use setCsv:

// Import button onclick functions
function importCSV() {
var file = document.getElementById("selectedFile").files[0];
let reader = new FileReader();
reader.readAsText(file);
reader.onload = function (event) {
var csv = event.target.result;
spread.getSheet(0).setCsv(0, 0, csv, "\r", ",");
}
}

Export CSV Data from JS App Using SpreadJS’s getCsv Method

Alternatively, to export CSV data, we need to use the getCsv method within the exportCSV function. This will require a little more code to enable the exported file to be downloaded from the browser so we can create a download function:

// Function to download the CSV file
const download = (data) => {
// Create a Blob with the CSV data and type
const blob = new Blob([data], { type: 'text/csv' });
// Create a URL for the Blob
const url = URL.createObjectURL(blob);
// Create an anchor tag for downloading
const a = document.createElement('a');
// Set the URL and download attribute of the anchor tag
a.href = url;
a.download = 'download.csv';
// Trigger the download by clicking the anchor tag
a.click();
}

Now that we have that function set up, we can retrieve the CSV content with the getCsv method and then pass that to the download function we just created:

// Export button onclick function
function exportCSV() {
console.log("export button");
var csvContent = spread.getSheet(0).getCsv(0, 0, spread.getSheet(0).getRowCount(), spread.getSheet(0).getColumnCount(), "\r", ",");
download(csvContent);
}

That’s all that is needed to import and export CSV files with SpreadJS:

Conclusion

With a small amount of SpreadJS code, you can add CSV import and export functionality to your app, providing your users the ability to load and save their data. For more information about SpreadJS and examples, check out our Demos and Documentation today!

Originally published at https://developer.mescius.com on June 7, 2024.

--

--

MESCIUS inc.
MESCIUS inc.

We provide developers with the widest range of Microsoft Visual Studio components, IDE platform development tools, and applications.