Install export-to-csv via npm
mainTo use this library in your project, install it using npm:
npm install --save export-to-csvrepository·main·Indexed 42 days ago
https://github.com/alexcaza/export-to-csvA lightweight, zero-dependency library for generating and downloading CSV data from JSON collections in both browser and Node.js environments. Version 1.5.0 provides utilities like generateCsv for data conversion, mkConfig for option merging, and browser-specific functions like download and asBlob for file handling.
To use this library in your project, install it using npm:
npm install --save export-to-csvIn Node.js, instead of using the download function (which is for browsers), you should use generateCsv to create the data and then write it to the file system using node:fs. You may need to convert the output using asString and Buffer to create a writable Uint8Array.
import { mkConfig, generateCsv, asString } from "export-to-csv";
import { writeFile } from "node:fs";
import { Buffer } from "node:buffer";
const csvConfig = mkConfig({ useKeysAsHeaders: true });
const mockData = [
{
name: "Rouky",
date: "2023-09-01",
percentage: 0.4,
quoted: '"Pickles"',
},
{
name: "Keiko",
date: "2023-09-01",
percentage: 0.9,
quoted: '"Cactus"',
},
];
const csv = generateCsv(csvConfig)(mockData);
const filename = `${csvConfig.filename}.csv`;
const csvBuffer = new Uint8Array(Buffer.from(asString(csv)));
// Write the csv file to disk
writeFile(filename, csvBuffer, (err) => {
if (err) throw err;
console.log("file saved: ", filename);
});In a browser environment, you can use mkConfig to merge your options with defaults, generateCsv to convert an array of objects into CSV data, and download to trigger a file download. The library uses ES modules.
import { mkConfig, generateCsv, download } from "export-to-csv";
// mkConfig merges your options with the defaults
const csvConfig = mkConfig({ useKeysAsHeaders: true });
const mockData = [
{
name: "Rouky",
date: "2023-09-01",
percentage: 0.4,
quoted: '"Pickles"',
},
{
name: "Keiko",
date: "2023-09-01",
percentage: 0.9,
quoted: '"Cactus"',
},
];
// Converts your Array<Object> to a CsvOutput based on the configs
const csv = generateCsv(csvConfig)(mockData);
// Trigger download on a button click
const csvBtn = document.querySelector("#csv") as HTMLButtonElement;
csvBtn.addEventListener("click", () => download(csvConfig)(csv));If you need to use browser-specific APIs (like Chrome Extension download methods) instead of the library's built-in download function, you can convert the CsvOutput into a Blob using asBlob.
import { mkConfig, generateCsv, asBlob } from "export-to-csv";
const csvConfig = mkConfig({ useKeysAsHeaders: true });
const mockData = [{ name: "Rouky", date: "2023-09-01" }];
const csv = generateCsv(csvConfig)(mockData);
// Generate the Blob from the CsvOutput
const blob = asBlob(csvConfig)(csv);
// Example: Using with URL.createObjectURL for Chrome Extensions
const url = URL.createObjectURL(blob);
// ... use url with chrome.downloads.downloadIn TypeScript, generateCsv returns a CsvOutput type rather than a raw string. This is a type-safety feature to prevent passing unformatted strings to the download function. To treat the output as a standard string, use the asString utility.
import { mkConfig, generateCsv, asString } from "export-to-csv";
const csvConfig = mkConfig({ useKeysAsHeaders: true });
const mockData = [{ name: "Rouky", date: "2023-09-01" }];
const csvOutput = generateCsv(csvConfig)(mockData);
// Use asString to unpack CsvOutput into a plain string
const csvString = asString(csvOutput);When using the library, you can provide a ConfigOptions object to customize the CSV generation process. If you do not provide certain options, the library uses the following default values:
| Option | Default Value | Description |
|---|---|---|
fieldSeparator | "," | The character used to separate fields. |
decimalSeparator | "." | The character used for decimal points. |
quoteStrings | true | Whether to wrap strings in quotes. |
quoteCharacter | " | The character used for quoting strings. |
showTitle | false | Whether to include a title in the output. |
title | "My Generated Report" | The title text if showTitle is true. |
filename | "generated" | The default filename. |
showColumnHeaders | true | Whether to include column headers. |
useTextFile | false | Whether to treat the output as a text file. |
fileExtension | "csv" | The file extension to use. |
mediaType | MediaType.csv | The MIME type for the output. |
useBom | true | Whether to include a Byte Order Mark (BOM). |
columnHeaders | [] | Custom column headers. |
useKeysAsHeaders | false | Whether to use object keys as headers. |
boolDisplay | { true: "TRUE", false: "FALSE" } | Mapping for boolean value display. |
replaceUndefinedWith | "" | String to use when a value is undefined. |
escapeFormulas | false | Whether to escape Excel-style formulas. |
// Example of overriding defaults
const myConfig = {
fieldSeparator: ";",
showTitle: true,
title: "Custom Report",
replaceUndefinedWith: "N/A"
};When using the library, you can provide a ConfigOptions object to control the structure and formatting of the generated CSV/TSV.
Key configuration properties include:
filename: The name of the file to be generated.fieldSeparator: The character used to separate fields (e.g., , or ;).quoteStrings: Boolean to determine if strings should be wrapped in quotes.quoteCharacter: The character used for quoting strings.decimalSeparator: The character used for decimal points.showColumnHeaders: Whether to include the header row.showTitle: Whether to include a title at the top of the file.title: The title text to display.fileExtension: The file extension to use (e.g., .csv).mediaType: The MIME type of the output (see MediaType for options).useBom: Whether to include a Byte Order Mark (BOM).columnHeaders: An array of ColumnHeader objects to define custom headers.useKeysAsHeaders: If true, uses the object keys from the data as headers.boolDisplay: An object mapping boolean values to display strings: { true: 'Yes', false: 'No' }.replaceUndefinedWith: A value (string, boolean, or null) to use when a field is undefined.escapeFormulas: Boolean to escape characters that might trigger spreadsheet formulas.Note: The useTextFile option is deprecated and will be removed in version 2.x.x. Use fileExtension instead.
const options: ConfigOptions = {
filename: 'export.csv',
fieldSeparator: ',',
showColumnHeaders: true,
mediaType: MediaType.csv,
boolDisplay: { true: 'TRUE', false: 'FALSE' },
replaceUndefinedWith: ''
};The generateCsv function accepts an options object to control the structure and formatting of the exported CSV. Key configuration areas include:
columnHeaders: Recommended for controlling order. An array of string (used for both lookup and label) or {key: string, displayLabel: string} (where key is the data lookup and displayLabel is the header text).showColumnHeaders: Boolean (default true). If false, the first row will contain data instead of headers.useKeysAsHeaders: Boolean (default false). Uses object keys as headers. Warning: Not recommended for large collections and does not guarantee column order. It overrides columnHeaders if set.fieldSeparator: The character used to separate fields (default `The mkConfig function is used to merge user-provided ConfigOptions with the library's internal defaults. This ensures that all required configuration keys are present in the resulting object, even if they were not explicitly provided by the user.
import { mkConfig } from 'export-to-csv';
const config = mkConfig({
fieldSeparator: '|',
showTitle: true
});
// config will contain all other default values merged with the overridesexport-to-csv package exports its entire public API from ./lib/index.ts. This includes the core functions and types required to generate CSV data in both browser and Node.js environments.Use generateCsv to transform an array of objects into a CsvOutput object. This function applies configuration options (like headers and BOM) to the provided data.
Note: If the resulting output is empty, it will throw a CsvGenerationError.
import { generateCsv } from 'export-to-csv';
const data = [
{ name: 'Alice', age: 30 },
{ name: 'Bob', age: 25 }
];
const config = { filename: 'users' };
const csvOutput = generateCsv(config)(data);The asBlob function converts a CsvOutput object into a browser Blob. This is useful for scenarios where you need to handle the file data manually, such as in browser extensions or custom upload logic.
The MIME type of the resulting Blob is determined by the mediaType or useTextFile configuration options.
import { generateCsv, asBlob } from 'export-to-csv';
const config = { filename: 'data', mediaType: 'text/csv' };
const csvOutput = generateCsv(config)(data);
const blob = asBlob(config)(csvOutput);