Skip to main content Skip to footer

How to Import and Export CSV Files Using Node.js

Quick Start Guide
Tutorial Concept

Learn how to build a Node.js CSV import/export workflow using SpreadJS, an enterprise JavaScript spreadsheet. This tutorial shows how to read a CSV file from a Node.js application, load the data into a JS workbook, update the spreadsheet with formulas, export the modified data back to CSV, and open the exported file in Excel.

What You Will Need
  • Node.js
  • @mescius/spread-sheets
  • express
  • puppeteer
  • Code editor (Visual Studio Code)
  • Modern browser runtime through Puppeteer
Controls Referenced

SpreadJS JavaScript Spreadsheet Component

In the dynamic world of web development, Node.js has established itself as a pivotal runtime environment for server-side scripting and automation. For web developers leveraging Node.js, managing data in various formats, like CSV, is a common yet critical task. Whether you're importing data, performing analytics, or structuring information in a tabular format, the ability to efficiently import, process, and export CSV files can significantly enhance your workflow.

SpreadJS provides spreadsheet functionality for JavaScript applications and includes built-in APIs for working with CSV data. Using the setCsv() method, CSV content can be loaded into a worksheet. Using the getCsv() method, worksheet data can be exported back into a delimited CSV string.

In this tutorial, we will build a modern Node.js workflow that reads an input.csv file, processes the data with SpreadJS, adds formulas, exports the updated content to output.csv, and opens the exported file in Excel.

Download a Trial and Get Started Using SpreadJS Today!

How to Read and Export CSV Files from a Node.js Application:

  1. Create a Node.js Project
  2. Install the Required Packages
  3. Project Structure
  4. Create the Input CSV FileCreate
  5.  the SpreadJS Runtime Page
  6. Create the Node.js Application
  7. Run the Application
  8. Review the Exported CSV File

Download a Finished Sample Application to Follow Along.


Create a Node.js Project

Create a new project folder:

mkdir spreadjs-node-csv
cd spreadjs-node-csv
npm init -y

Install the Required Packages

Install SpreadJS, Express, and Puppeteer:

npm install @mescius/spread-sheets express puppeteer

Express is used to serve the local HTML page and SpreadJS assets. Puppeteer provides a browser runtime where SpreadJS can execute reliably while Node.js handles file reading and writing.


Project Structure

After creating the files, your project should look like this:

Node.js CSV Excel Import/Export Project Sample Structure | Developer Tutorial

The output.csv file will be created after running the application.


Create the Input CSV File

Create a file named input.csv in the root project folder.

Product,Quantity,Price
Laptop,2,1200
Monitor,3,250
Keyboard,5,80

This file contains the original CSV data that will be imported into SpreadJS.


Create the SpreadJS Runtime Page

Inside the public folder, create a file named spread.html. This file acts as the browser runtime layer where SpreadJS performs spreadsheet processing before returning the updated CSV data back to the Node.js application.

The first step is initializing a SpreadJS workbook instance and accessing the active worksheet.

const spread = new GC.Spread.Sheets.Workbook(
  document.getElementById("ss")
);

const sheet = spread.getActiveSheet();

Before importing the CSV file, the raw input is normalized to ensure consistent line endings across different operating systems.

const normalizedCsv = csvText
  .replace(/\r\n/g, "\n")
  .replace(/\r/g, "\n")
  .trim();

Next, the CSV content is loaded into the worksheet using the setCsv() method.

sheet.setCsv(0, 0, normalizedCsv, "\n", ",");

Once the data is imported, additional spreadsheet calculations can be applied. In this example, a new Total column is added and formulas calculate the total price for each product.

sheet.setFormula(1, 3, "=B2*C2");
sheet.setFormula(2, 3, "=B3*C3");
sheet.setFormula(3, 3, "=B4*C4");

Finally, the updated worksheet is exported back into CSV format using the getCsv() method.

return sheet.getCsv(0, 0, 6, 4, "\r\n", ";");

The semicolon delimiter is used during export to ensure the generated CSV opens correctly in spreadsheet applications such as Excel, especially on systems where the default regional separator is not a comma.


Create the Node.js Application

Next, create a file named app.js in the project root. This file handles the server-side workflow by reading the input CSV file, launching a browser runtime, executing the SpreadJS processing logic, and exporting the updated CSV file.

The first step is importing the required Node.js modules and dependencies.

const fs = require("fs");
const path = require("path");
const express = require("express");
const puppeteer = require("puppeteer");
const { exec } = require("child_process");

Next, configure an Express server that will serve both the SpreadJS assets and the runtime HTML page.

const app = express();

app.use("/node_modules",
  express.static(path.join(__dirname, "node_modules"))
);

app.use(
  express.static(path.join(__dirname, "public"))
);

The application then reads the source CSV file using the Node.js fs module.

const csvText = fs.readFileSync(
  path.join(__dirname, "input.csv"),
  "utf8"
);

To execute SpreadJS, a browser runtime is launched using Puppeteer, which loads the spread.html page created in the previous step.

const browser = await puppeteer.launch({
  headless: "new"
});

const page = await browser.newPage();

await page.goto(
  "http://localhost:3000/spread.html"
);

Once the page is loaded, the CSV content is passed into the browser context where SpreadJS processes the worksheet and returns the updated CSV output.

const outputCsv = await page.evaluate((csv) => {
  return window.processCsvWithSpreadJS(csv);
}, csvText);

Finally, the exported CSV content is written into a new file and automatically opened after the process completes.

fs.writeFileSync(
  path.join(__dirname, "output.csv"),
  outputCsv
);

exec('start "" "output.csv"');

This file manages the Node.js side of the workflow by reading the original CSV file, launching a browser environment with Puppeteer, executing the SpreadJS spreadsheet logic, exporting the processed data into a new CSV file, and automatically opening the generated output.


Run the Application

Run the application from the terminal:

node app.js

The console will display output similar to this:

Running Console Application | Reading and Processing CSV files in Node.js Applications

After the script finishes, a new output.csv file is created in the project folder and opened automatically.


Review the Exported CSV File

The exported file contains the original product data, a calculated Total column, and a Grand Total row.

Export .csv File Contents | Node.js Read/Export .CSV Excel Files

When opened in Excel, the semicolon-delimited CSV displays the values in separate columns.

Node.js .csv File Export Example


Conclusion

In this tutorial, we built a Node.js CSV import/export workflow using SpreadJS. The application reads CSV data from a local file, loads it into a SpreadJS worksheet, applies spreadsheet formulas, exports the updated worksheet data back to CSV, and opens the result in Excel.

This approach is useful for server-driven workflows where Node.js handles file operations while SpreadJS provides spreadsheet calculation and CSV processing capabilities in a browser runtime.

Download a Trial and Get Started Using SpreadJS Today!

Tags:

comments powered by Disqus