How to Import and Export CSV Files Using JavaScript
Tags: webdev, devops, javascript, tutorial
Published: 2024-06-28 14:55:45

---
canonical_url: https://developer.mescius.com/blogs/how-to-import-and-export-csv-files-using-javascript
description: Learn how to import and export CSV files using JavaScript. See more from SpreadJS today.
---
**What You Will Need**
- SpreadJS
- NPM
- Visual Studio Code

**Controls Referenced**
- [SpreadJS](https://developer.mescius.com/spreadjs/docs/overview)

**Tutorial Concept**

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

---
![SJS CSV](//cdn.mescius.io/umb/media/psblfeml/sjs-csv.png?rmode=max&width=725&height=408)

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 [](https://developer.mescius.com/spreadjs "https://developer.mescius.com/spreadjs") [**SpreadJS**](https://developer.mescius.com/spreadjs "https://developer.mescius.com/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](#SpreadJS)
2.  [Add HTML Buttons for Import and Export](#Buttons)
3.  [Import CSV Data to JS App Using SpreadJS’s setCsv Method](#Import)
4.  [Export JS Data to a CSV File Using SpreadJS’s getCsv Method](#Export)

To follow along with this tutorial, you can [download the sample](https://cdn.mescius.io/umb/media/u1lbwpaq/spreadjscsvio.zip). 

## <a id="SpreadJS"></a>Add SpreadJS to a JavaScript App

To get started with this example, create an app, [reference SpreadJS’s files](https://developer.mescius.com/spreadjs/docs/getstarted/quick-start/referencing-spreadjs "https://developer.mescius.com/spreadjs/docs/getstarted/quick-start/referencing-spreadjs"), and [initialize the JavaScript spreadsheet component](https://developer.mescius.com/spreadjs/docs/getstarted/quick-start/initializing-spreadjs "https://developer.mescius.com/spreadjs/docs/getstarted/quick-start/initializing-spreadjs"). 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:

![SJS IO CSV Data](//cdn.mescius.io/umb/media/tjhejg40/sjs-i-o-csv-data.png?rmode=max&width=740&height=398)

## <a id="Buttons"></a>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](https://www.w3schools.com/jsref/event_onclick.asp "https://www.w3schools.com/jsref/event_onclick.asp") 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 Export Csv Console](//cdn.mescius.io/umb/media/aurfqvqd/import-export-csv-console.gif?rmode=max&width=758&height=379)

## <a id="Import"></a>Import CSV Data to JS App Using SpreadJS’s setCsv Method

To import CSV data, invoke SpreadJS’s [**setCsv** method](https://developer.mescius.com/spreadjs/api/classes/GC.Spread.Sheets.Worksheet#setCsv "https://developer.mescius.com/spreadjs/api/classes/GC.Spread.Sheets.Worksheet#setCsv") 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", ",");
        }
    }
```

## <a id="Export"></a>Export CSV Data from JS App Using SpreadJS’s getCsv Method

Alternatively, to export CSV data, we need to use the [**getCsv** method](https://developer.mescius.com/spreadjs/api/classes/GC.Spread.Sheets.Worksheet#getcsv "https://developer.mescius.com/spreadjs/api/classes/GC.Spread.Sheets.Worksheet#getcsv") 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:

![Import Export Csv From Browser](//cdn.mescius.io/umb/media/yw1mjpmv/import-export-csv-from-browser.gif?rmode=max&width=744&height=372)

## 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](https://developer.mescius.com/spreadjs/demos/ "https://developer.mescius.com/spreadjs/demos/") and [Documentation](https://developer.mescius.com/spreadjs/docs/overview "https://developer.mescius.com/spreadjs/docs/overview") today!