export-to-csv

repository·main·Indexed 42 days ago

https://github.com/alexcaza/export-to-csv

A 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.

Tokens
4.3K
Snippets
15
Records
19
Agent score
53%

What's inside export-to-csv

  1. Use export-to-csv in Node.js

    main

    In 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);
    });
  2. Use export-to-csv in the browser

    main

    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));
  3. Convert CsvOutput to a Blob using asBlob

    main

    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.download
  4. Convert CsvOutput to a string using asString

    main

    In 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);
  5. Configure export-to-csv options

    main

    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:

    OptionDefault ValueDescription
    fieldSeparator","The character used to separate fields.
    decimalSeparator"."The character used for decimal points.
    quoteStringstrueWhether to wrap strings in quotes.
    quoteCharacter"The character used for quoting strings.
    showTitlefalseWhether to include a title in the output.
    title"My Generated Report"The title text if showTitle is true.
    filename"generated"The default filename.
    showColumnHeaderstrueWhether to include column headers.
    useTextFilefalseWhether to treat the output as a text file.
    fileExtension"csv"The file extension to use.
    mediaTypeMediaType.csvThe MIME type for the output.
    useBomtrueWhether to include a Byte Order Mark (BOM).
    columnHeaders[]Custom column headers.
    useKeysAsHeadersfalseWhether 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.
    escapeFormulasfalseWhether to escape Excel-style formulas.
    // Example of overriding defaults
    const myConfig = {
      fieldSeparator: ";",
      showTitle: true,
      title: "Custom Report",
      replaceUndefinedWith: "N/A"
    };
  6. Configure export options with ConfigOptions

    main

    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: ''
    };
  7. Configure `generateCsv` options

    main

    The generateCsv function accepts an options object to control the structure and formatting of the exported CSV. Key configuration areas include:

    Column and Header Management

    • 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.

    Formatting and Delimiters

    • fieldSeparator: The character used to separate fields (default `
  8. Initialize configuration with `mkConfig`

    main

    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 overrides
  9. Generate CSV data with generateCsv()

    main

    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);
  10. Convert CsvOutput to a Blob with asBlob()

    main

    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);