Skip to content
Eric Damtoft edited this page Dec 4, 2018 · 4 revisions

Installation

NPM

npm install csvexport --save
import CsvExport from "csvexport";

const exporter = CsvExport.create();

CDN

<script src="https://unpkg.com/csvexport"></script>
<script>
const exporter = CsvExport.create();
</script>

Usage

Create an Exporter

The create function instantiates an exporter configured with your supplied options. An exporter can be used repeatedly to download different datasets of the same confuiguration.

import CsvExport from "csvexport";

const config = { filename: "myexport.csv" };

const exporter = CsvExport.create(config);

Download

use the downloadCsv(data) function to automatically initiate a download. This should work in all modern browsers and IE11.

const data = [
 { foo: "Bar" }, { foo: "Baz" }
]

exporter.downloadCsv(data);

Additionally, if you want more control over the download, you can get a raw blob by calling createCsvBlob(data)

Configuration

the "create" function takes an optional object with supports the following properties:

  • delimiter: specify a custom delimeter (string; optional; default = ",")
  • contentType: specity a custom contentType (string; optional; default = "text/csv")
  • filename: a name for the file to download (string; options; default = "export.csv")
  • includeHeaders: choose to include or exclude the headers as the first row (boolean; optional; default = true)
  • columns: choose which columns to include. If not specified, will use the properties of the first data item (array; optional)
  • headers: object which maps property names to headers (object; optional)
  • formatters: object which maps property names to a function which will return the formatted value (object; optional)
  • byteOrderMark: A unicode character to be placed at the beginning of the file to help open utf-8 csv in excel (string; optional)

Examples

Create a tab separated values file

import CsvExport from "csvexport";

const exporter = CsvExport.create({
  delimiter: "\t",
  contentType: "text/tab-separated-values",
  filename: "some-filename.tsv",
  includeHeaders: "false",
  columns: ["name","age"],
  headers: {
    name: "Person's Name",
    age: "Person's Age"
  },
  formatters: {
    age: age => age + " years old"
  },
  byteOrderMark: '\uFEFF' // for UTF-8 support in Excel
});

exporter.downloadCsv(people);

Clone this wiki locally