Skip to main content Skip to footer

How to Import and Export CSV Files Using Angular

Quick Start Guide
Tutorial Concept

Learn how to create a CSV import/export spreadsheet using SpreadJS in an Angular application. You can import CSV files, edit data directly in the grid, and export updated data back to CSV.

What You Will Need

Environment

  • Angular 20
  • TypeScript

Libraries:

Tools:

  • Code editor (Visual Studio Code recommended)
  • Modern browser (Chrome, Edge, Firefox)
Controls Referenced

SpreadJS Angular Spreadsheet Component

Documentation

In the dynamic world of web development, Angular stands out as a powerful framework. As Angular developers, we frequently handle data in various formats, with CSV files a common requirement. Whether it's importing data from external sources, performing data analysis, or presenting information in a structured format, mastering CSV file manipulation is crucial. In this blog, we'll delve into handling CSV files using SpreadJS, a robust spreadsheet component for Angular. You'll learn how to import, visualize, and export CSV data seamlessly within an Angular application. Let's explore the capabilities of effortless CSV file management in Angular development.

Steps to Add CSV Import/Export to Angular Apps

  1. Create an Angular Project
  2. Install SpreadJS Packages
  3. Configure SpreadJS CSS
  4. Create the Angular Spreadsheet Component
  5. Add Imports
  6. Component Declaration
  7. Initialize the Spreadsheet
  8. Implement CSV Import Logic
  9. Implement CSV Export Logic
  10. Run Your Angular Application

Download a Trial of SpreadJS Today!


Create an Angular Project

Start by creating a new Angular project using Angular CLI. This project will host the spreadsheet component and handle CSV import/export.

npm install -g @angular/cli
ng new angular-import-export-csv --style=css --ssr=false
cd angular-import-export-csv

Install SpreadJS Packages

Using npm install the SpreadJS core library and the Angular wrapper. These packages allow you to render the spreadsheet component and work with CSV data. Also install the FileSaver library to save CSV files in the browser:

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

Configure SpreadJS CSS

Developers can select a pre-built Excel themes for the Angular spreadsheet control. Configure the SpreadJS control’s theme by importing the selected theme in the styles.css file. For example this is setting the Excel 2013 White theme.

@import "@mescius/spread-sheets/styles/gc.spread.sheets.excel2013white.css";

Create the Angular Spreadsheet Component

We will create a component with a toolbar for CSV import/export and a SpreadJS spreadsheet grid.

The toolbar contains a hidden file input for CSV import and buttons for importing and exporting. The <gc-spread-sheets> component displays the spreadsheet.

<div id="toolbar" style="margin-bottom: 10px">
  <input #fileInput type="file" accept=".csv" style="display:none" (change)="handleFileImport($event)" />

  <button (click)="triggerImport(fileInput)">Import CSV</button>
  <button (click)="exportCsv()">Export CSV</button>
</div>

<gc-spread-sheets 
  [backColor]="spreadBackColor" 
  [hostStyle]="hostStyle"
  (workbookInitialized)="workbookInit($event)">
</gc-spread-sheets>

This layout provides a toolbar for CSV operations and a container for the spreadsheet grid.

Create an Angular Spreadsheet Application to Import/Export .csv Files

This layout provides a toolbar for CSV operations and a container for the spreadsheet grid.


Add Imports

We start by adding all the necessary library imports at the top of app.ts. This ensures we have access to Angular core features, SpreadJS, the Angular SpreadJS module, and the FileSaver library for downloading CSV files.

import { Component } from '@angular/core';
import * as GC from '@mescius/spread-sheets';
import { SpreadSheetsModule } from '@mescius/spread-sheets-angular';
import { saveAs } from 'file-saver';

Component Declaration

Next, we define the Angular component. We set it as standalone and import the SpreadSheetsModule so the <gc-spread-sheets> component can be used directly in the template. We also declare properties to hold the SpreadJS workbook instance, the active worksheet, and some basic UI styles.

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [SpreadSheetsModule],
  templateUrl: './app.html',
  styleUrls: ['./app.css']
})
export class AppComponent {
  spread!: GC.Spread.Sheets.Workbook; // The SpreadJS workbook instance
  sheet!: GC.Spread.Sheets.Worksheet; // The active worksheet

  spreadBackColor = 'aliceblue'; 
  hostStyle = { width: '100%', height: '600px' }; 

Initialize the Spreadsheet

Once the <gc-spread-sheets> component initializes, we capture the spread instance and the active sheet. This allows us to programmatically interact with the spreadsheet, set default values, and prepare it for CSV import/export.

 // Initialize the Spreadsheet after view is ready
  workbookInit(args: { spread: GC.Spread.Sheets.Workbook }) {
    this.spread = args.spread;
    this.sheet = this.spread.getActiveSheet();

    // Optional initial content
    this.sheet.setValue(0, 0, 'Hello SpreadJS + Angular!');
    this.sheet.setValue(1, 0, "Click 'Export CSV' to download this data.");
  }

Implement CSV Import Logic

To import CSV files, we use a hidden file input and the browser’s FileReader API. SpreadJS parses the CSV data into the grid using the setCsv() method. This logic replaces any existing data with the new CSV content.

    // Handle CSV import
  handleFileImport(event: any) {
    const file = event.target.files[0];
    if (!file) return;
    const reader = new FileReader();
    reader.onload = (e: any) => {
      // Import CSV into SpreadJS
      this.sheet.setCsv(0, 0, e.target.result, '\n', ',');
    };
    reader.readAsText(file);
    // Reset input so same file can be re-imported
    event.target.value = '';
  }

After selecting a CSV file, the spreadsheet grid will instantly populate with the imported data, as illustrated in the image below.

Import CSV Files into Angular Applications


Implement CSV Export Logic

Exporting the spreadsheet data back to CSV uses SpreadJS’s getCsv() method. The CSV string is converted to a Blob and downloaded using the file-saver library.

   // Export CSV
  exportCsv() {
    const csv = this.sheet.getCsv(
      0,
      0,
      this.sheet.getRowCount(),
      this.sheet.getColumnCount(),
      '\n',
      ','
    );
    const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
    saveAs(blob, 'exported-spreadsheet.csv');
  }
}

This ensures users can export exactly what they see in the spreadsheet, including any edits made in the grid.

Export CSV Files from Angular Applications


Run Your Angular Application

Start the Angular development server:

ng serve

Open your browser at http://localhost:4200. You can now import CSV files into the spreadsheet, edit them directly in the grid, and export the updated data back to CSV. 


Download a Trial of SpreadJS Today!

Conclusion

SpreadJS, combined with Angular, offers a powerful and flexible way to handle CSV data directly within modern web applications. By leveraging the getCsv() and setCsv() methods, developers can quickly create interactive, Excel-like spreadsheet experiences that allow users to import, edit, and export CSV files seamlessly. This Angular and SpreadJS CSV workflow is ideal for enterprise applications that require lightweight integration, high performance, and full control over the user 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