Skip to main content Skip to footer

How to Import and Export CSV Files Using JavaScript

Quick Start Guide
Tutorial Concept

Learn how to create a JavaScript CSV import/export Spreadsheet using the JavaScript spreadsheet component, SpreadJS, to import and export CSV files directly in your web application.

What You Will Need

Environment: JavaScript (Vanilla) Environment

Libraries:

Tools:

  • Code Editor – Visual Studio Code
  • Modern browser (Chrome, Edge, Firefox)
Controls Referenced

SpreadJS JavaScript Spreadsheet Component

Documentation

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.

Steps to Add CSV Import/Export Abilities to JavaScript Apps

  1. Create Your JavaScript Project for CSV Import/Export
  2. Add the Spreadsheet Container and Toolbar
  3. Add Imports
  4. Initialize the Spreadsheet
  5. Implement CSV Import Logic
  6. Implement CSV Export Logic
  7. Run Your Application

Download a Trial of SpreadJS Today!


Create Your JavaScript Project for CSV Import/Export

To start building your CSV import/export functionality with SpreadJS, the first step is to create a clean JavaScript project structure using Vite. Vite is a modern build tool that allows you to work with ES modules and run a fast development server, which makes it perfect for vanilla JavaScript projects.

First, create a new folder for your project. For example, you could call it csv-spread. Inside this folder, initialize a new Vite project using the terminal:

npm create vite@latest

Follow the prompts, selecting a vanilla JavaScript project. Once Vite sets up your project, you will have a folder structure similar to this:

js-csv-spreadsheet/
 ├─ index.html
 ├─ package.json
 └─ src/
     └─ main.js

Next, install the required dependencies for SpreadJS and FileSaver via npm. SpreadJS provides the spreadsheet component and CSV import/export methods, while FileSaver is used to save CSV files in the browser:

npm install @mescius/spread-sheets 
npm install file-saver

This sets up the project to start working with SpreadJS.


Add the Spreadsheet Container and Toolbar

In your index.html, add a file input, two buttons for import/export, and a container div for the spreadsheet. This sets up the user interface, allowing CSV files to be loaded and exported easily.

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>CSV Import Export</title>
</head>
<body>
<input type="file" id="file">
<button id="import">Import CSV</button>
<button id="export">Export CSV</button>
<div id="hostElement" style="width:100%;height:600px;border:1px solid gray"></div>
<script type="module" src="/src/main.js"></script>
</body>
</html>

Add Imports

In src/main.js, import SpreadJS and FileSaver.

import * as GC from "@mescius/spread-sheets";
import "@mescius/spread-sheets/styles/gc.spread.sheets.excel2013white.css";
import { saveAs } from "file-saver";

Initialize the Spreadsheet

In the same file, initialize the workbook and active sheet:

let workbook = new GC.Spread.Sheets.Workbook("hostElement");
let sheet = workbook.getActiveSheet();

This confirms that the spreadsheet is fully interactive and ready to import or export CSV data.

Initialize a JavaScript Spreadsheet Application


Implement CSV Import Logic

Connect the import button to a hidden file input using the FileReader API. Once a CSV file is selected, read it and load it into the spreadsheet with setCsv() which parses the CSV data and renders it directly into the spreadsheet grid for immediate viewing and editing.

// IMPORT
document.getElementById("import").onclick = () => {
  let file = document.getElementById("file").files[0]
  if (!file) return
  let reader = new FileReader()
  reader.onload = e => {
    sheet.setCsv(0, 0, e.target.result, "\n", ",")
  }
  reader.readAsText(file)
}

This logic ensures that any existing data is cleared, the CSV data is correctly parsed, and the spreadsheet updates instantly after the file is selected.

Import CSV Files to JavaScript Applications


Implement CSV Export Logic

To export the current spreadsheet content as CSV, use getCsv() to retrieve the data, convert it to a Blob, and download using FileSaver. The exported file is named exported-spreadsheet.csv:

// EXPORT
document.getElementById("export").onclick = () => {
  let csv = sheet.getCsv(
    0,
    0,
    sheet.getRowCount(),
    sheet.getColumnCount(),
    "\n",
    ","
  )
  let blob = new Blob([csv], { type: "text/csv;charset=utf-8;" })
  saveAs(blob, "exported-spreadsheet.csv")
}

This allows users to export exactly what they see in the spreadsheet after editing to a CSV file.

Export JavaScript Spreadsheet Data to a CSV File


Run Your Application

To run the project locally, use a simple local server such as Vite or VS Code Live Server. If you are using Vite, you can start the development server with the following command in your project directory:

npm run dev

Once the server is running, open your browser at the address provided by Vite (usually http://localhost:5173) to see your interactive spreadsheet.

If you prefer VS Code Live Server, simply right click index.html in your project and select “Open with Live Server”. The page will load in your browser, and you can use the import/export functionality in the same way.


Download a Trial of SpreadJS Today!

Conclusion

Using SpreadJS with plain JavaScript, it is simple to create a fully interactive CSV spreadsheet in the browser. The getCsv() and setCsv() methods handle all CSV parsing and exporting seamlessly, providing an Excel-like experience without requiring Excel or backend processing. This workflow is ideal for lightweight, high-performance applications where users need to import, edit, and export CSV data directly in a web interface.

For more features, demos, and detailed guidance, be sure to check out the SpreadJS product and documentation, where you can explore additional capabilities and examples to enhance your spreadsheet applications.

Tags:

comments powered by Disqus