Git Product home page Git Product logo

export-to-csv's Introduction

Hey, I'm Alex (he/him) πŸ‘‹πŸ»

I'm a senior full-stack product engineer.

  • πŸ‘¨πŸ»β€πŸ’» I've been building on the web for ~15 years
  • πŸ§ͺ I love jamming with product teams to help solve people's problems
  • πŸ§‘πŸ»β€πŸŽ¨ I believe engineers should spend more time learning about design thinking
  • 🀝 I think cross-team collaboration/ideation/planning should be baked into product processes

Curious about what makes a product engineer? I tried to define the role here:
https://alexcaza.com/personal/the-rise-of-product-engineering/

export-to-csv's People

Contributors

ahmed-anas avatar alexcaza avatar arf1980 avatar devlavshah avatar divyaswormakai avatar hukacode avatar javiertelioz avatar jmann-tw avatar makotoishida avatar rgansevles avatar richard-peterson-at-lifelogic avatar sn123 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

export-to-csv's Issues

Support ES6 Modules

Hello Alex,
when importing your script into typescript Angular projects, the following warning appears:

Warning: [file] depends on 'export-to-csv'. CommonJS or AMD dependencies can cause optimization bailouts.
For more info see: https://angular.io/guide/build#configuring-commonjs-dependencies

I have reviewed the source code here and it seems like this project is not yet a ES Module.
The root project, which is the basis of this fork, seems to have made this change in 2018 in this commit. As you can see, they introduce a new module attribute in the package.json file.

For any modern typescript project, it would be helpful if you could provide a ES Module of your fork.

You can read more about the benefits of ESM here: https://dev.to/costamatheus97/es-modules-and-commonjs-an-overview-1i4b

Let me know if I can help during the implementation of this.

Best,
Alexander

Browser support

BUG REPORT

This library does the job quite well, but it could do a bit better, safari mobile browser doesn't download the CSV file, instead it just displays it in browser, could this be solved?

Failed to parse source map

In my React application, I am getting issue like Error: ENOENT: no such file or directory, open \node_modules\export-to-csv\build\export-to-csv.js.map', Please help me for resolving this issue.

issue

Dynamic data getting only first column.

if I have two rows like this,

const abc = [
{u1:'U', p1: 'R' },
{u1:'L', p1:'K', u2:'S', p2:'T'}
]

It gives result like this

u1 p1
U R
L K

but it should be

u1 p1 u2 p2
U R
L K S T

Boolean Value Automatically Converted into Uppercase in CSV File.

data ==>

[
{
name: 'Test 1',
age: 13,
average: 8.2,
status: true,
description: "Sample Text"
},
{
name: 'Test 2',
status: true,
description: "Sample Text"
}
]

const csvExporter = new ExportToCsv(options);
csvExporter.generateCsv(data);

CSV File has been download successfully but status column shows in uppercase format. As a little search in google, I've found that automatically Boolean values converts into uppercase format in CSV File.

Is any existing property we've to solve this problem? [OR] Any plans for update regarding this issue.

Note: Even If I explicitly convert as string ====> status: 'true', It's not helping too... We need to do while writing on file itself need to mention like text

ExportToCsv?

I tried running your sample code and got the following error

TypeError: ExportToCsv is not a constructor

Typechecking not strict enough during development

Describe the bug
Typescript seems to lift CsvOutput to string automatically despite it being a NewType, so comparing the result of generateCsv to string won't give a type error.

This can be see in this comment on PR #79.

The cause is unknown currently, but it's suspected to be a tsconfig.json setting that's missing, causing relaxed typechecking.

Expected behavior
CsvOutput should not be comparable to a string without using unpack/asString internally.

Error on empty data

How to reproduce

Run

import { ExportToCsv } from 'export-to-csv';

const csvExporter = new ExportToCsv({
  showLabels: true,
  headers: ['First', 'Second'],
});
const data = [];
csvExporter.generateCsv(data);

Expected result

The following CSV file is produced:

First,Second

Actual result

An exception is throw: Β«Cannot convert undefined or null to objectΒ».

image

upgrading to v1.2.3 broke functionality

after reinstalling my packages today, I got export-to-csv v1.2.3, which caused my project not to compile; freezing the version at 1.2.2 restored functionality.

having 1.2.3 installed, then the command npm start, produces the error:
Failed to compile.

./src/appReportTables/reportTableHelpers.js
Module not found: Can't resolve 'export-to-csv' in [...path../appReportTables]

macOS ventura 13.6.3

file referencing export-to-csv (in use with tanstack table)

import { jsPDF } from 'jspdf'; 
import autoTable from 'jspdf-autotable';
import { mkConfig, generateCsv, download } from 'export-to-csv'; 

export const handleExportRows = (table, subject, format) => {
  const CSV = 'csv'
  const subjectChoice = typeof(subject) === 'string' ? subject : 'data';
  const FW_FILENAME = `fleetwatcher-${subjectChoice}-`;
  const formatChoice = typeof(format) === 'string' && format.toLowerCase() === CSV ? 'csv' : 'pdf'; // maybe more later ??
  const visibleCols = table.getAllColumns().filter((c) => 
    c.columnDef.header.length > 0 && c.getIsVisible()
  );
  const visibleRows = table.getFilteredRowModel().rows;
  const tableHeaders = visibleCols.map((c) => c.columnDef.header);
  const tableData = visibleRows.map((r) => visibleCols.map((c) => r.original[c.id]));
  const dateStamp = (new Date()).toISOString().replace(/[^0-9]/g, "").slice(0, -3);
  if (formatChoice === 'pdf') {
    const doc = new jsPDF();
    autoTable(doc, {
      head: [tableHeaders],
      body: tableData,
    });
    doc.save(FW_FILENAME + dateStamp + '.pdf');
  } else { // CSV; maybe more formats later ??
    const csvConfig = mkConfig({
      fieldSeparator: ',',
      decimalSeparator: '.',
      filename: FW_FILENAME + dateStamp + '.csv',
      columnHeaders: visibleCols.map((c) => { return {key: c.id, displayLabel: c.columnDef.header}})
    });
    const rowData = visibleRows.map((row) => row.original);
    const csv = generateCsv(csvConfig)(rowData);
    download(csvConfig)(csv);
  }
};

Ability to change extension

It would be awesome if you would add the ability to change the extension. For example, if someone would like to export *.txt

Error when using in ESM project

Describe the bug

When using this library in a project set to use ESM project fails to build with import error:

export-to-csv/output/index.d.ts:1:15 - error TS2834: Relative import paths need explicit file extensions in EcmaScript imports when '--moduleResolution' is 'node16' or 'nodenext'. Consider adding an extension to the import path.

To Reproduce
Steps to reproduce the behavior:

  1. Create a new project, or open existing
  2. Ensure project is set to use ESM (moduleResolution: node16)
  3. Build project
  4. See error

When I get a few minutes I'll put an example repo together if needed.

Expected behavior
Project should build.

Desktop (please complete the following information):

  • OS: Unix
  • Browser nodejs
  • Version 20

Field Separator should include the "sep" keyword

First line of the generated file should define what the separator character should be. Without that, software like Excel can't understand what to do.

This is good:

sep=~
"Column A"~"Column B"~"Column C"
"Line A 1"~"Line A 2"~"Line A 3"
"Line B 1"~"Line B 2"~"Line B 3"
"Line C 1"~"Line C 2"~"Line C 3"

image

This is bad:

"Column A"~"Column B"~"Column C"
"Line A 1"~"Line A 2"~"Line A 3"
"Line B 1"~"Line B 2"~"Line B 3"
"Line C 1"~"Line C 2"~"Line C 3"

image

Add a returnBlob param in config

Hi,

I need to just have the blob.
So I updated your code like this :

const options = { fieldSeparator: ',', quoteStrings: '"', decimalSeparator: '.', showLabels: true, showTitle: true, title: 'My Awesome CSV', useTextFile: false, useBom: true, useKeysAsHeaders: true, returnBlob : true // headers: ['Column 1', 'Column 2', etc...] <-- Won't work with useKeysAsHeaders present! };

And in the export-to-csv.js at line 86 I added :

if(this._options.returnBlob){ return blob; }else{ if (navigator.msSaveBlob) { var filename = this._options.filename.replace(/ /g, "_") + fileExtension; navigator.msSaveBlob(blob, filename); } else { var attachmentType = this._options.useTextFile ? 'text' : 'csv'; var uri = 'data:attachment/' + attachmentType + ';charset=utf-8,' + encodeURI(this._csv); var link = document.createElement("a"); link.href = URL.createObjectURL(blob); link.setAttribute('visibility', 'hidden'); link.download = this._options.filename.replace(/ /g, "_") + fileExtension; document.body.appendChild(link); link.click(); document.body.removeChild(link); } }

If you want to implement ;-)

thanks a lot.

npm version is outdated

It stills contains the typo on decimalSeparator (should be camel case, fixed by PR #7) which causes a lot of headaches until you find the cause πŸ˜….

npm i export-to-csv

cat node_modules/export-to-csv/build/export-to-csv.js | grep decimal

Handling of inconsistent object definitions

I've encountered an issue where we're creating CSV from a list of objects. The objects vary in that they share a base set of keys, but also have ad-hoc keys that exist in some objects, but not all of them.

The actual output includes a lot of "undefined" and "null" which is not very useful for a CSV file. The expected behaviour is to treat any null or undefined as a blank string instead for the purpose of transforming to CSV.

Example Input:

[
  { "key1": "Value 1", "key2": "Value 2", "key3": "Value 3"},
  { "key1": "Value 1", "key2": "Value 2", "key4": "Value 4"},
]

Example Output:

key1,key2,key3,key4
Value 1, Value 2, Value 3, undefined
Value 1, Value 2, undefined, value 4

Expected Output:

key1,key2,key3,key4
Value 1, Value 2, Value 3,
Value 1, Value 2,, value 4

How do I change name of the file on website?

Describe the bug
A clear and concise description of what the bug is. If possible, include the data you're trying to export as a CSV (with any sensitive data removed; reduced test cases are welcomed).

To Reproduce
Steps to reproduce the behavior:

  1. Go to '...'
  2. Click on '....'
  3. Scroll down to '....'
  4. See error

Expected behavior
A clear and concise description of what you expected to happen.

Screenshots
If applicable, add screenshots to help explain your problem.

Desktop (please complete the following information):

  • OS: [e.g. iOS]
  • Browser [e.g. chrome, safari]
  • Version [e.g. 22]

Smartphone (please complete the following information):

  • Device: [e.g. iPhone6]
  • OS: [e.g. iOS8.1]
  • Browser [e.g. stock browser, safari]
  • Version [e.g. 22]

Double quotes are not escaped, they should when quote character is double quote

When the data contains a double quote, the csv format gets mixed up if the quote character is also a double quote.

According to RFC 4180 they must be escaped by another double quote:

If double-quotes are used to enclose fields, then a double-quote
appearing inside a field must be escaped by preceding it with
another double quote. For example:

   "aaa","b""bb","ccc"

Currently this seems not implemented

',' separator not being recognised

Hi everyone!

I'm coming across an issue where the exported csv is not properly formatted. Looks like excel doesn't recognise the "," as the field separator. It has happened to users both using win and macos. Checked their regional config and all seems to be alright.

image

Here's the params I'm passing to export-to-csv. Am I missing any details in the config? Thank you.

image

How to parse nested JSON properties?

Is there any way to parse nested JSON properties ? Currently, it shows them as [OBJECT]

         {
            name: 'Rouky',
            date: '2023-09-01',
            percentage: 0.4,
            quoted: '"Pickles"',
            Service: {
               active: 'yes',
               limit: 1,
            },
         },

How to add Multiple Headers. i.e subheaders

I'm trying to export a table which has one common headers and then subheaders. I've attached an image of the result that i want to achieve. From the image you can see that january has three subheaders: cost price, selling price & quantity. If there is any way to achieve this then please share.
[](url
example
)

Examples don't work in TypeScript for Node.js

Describe the bug
The examples in the readme do not work in Typescript for nodejs.

To Reproduce
Steps to reproduce the behavior:

  1. Run touch example.ts
  2. Put the contents of the Node.js example in said file
  3. Create a package.json with the following in it:
     {
       "dependencies": {
         "@types/node": "^20.11.20",
         "export-to-csv": "^1.2.3",
         "typescript": "^5.3.3"
       }
     }
    
  4. Run yarn.
  5. Run node_modules/.bin/ts-node ./example.ts

Expected behavior
The example would run.

Screenshots
This is the output:

$ node_modules/.bin/ts-node ./example.ts
/home/wheeler/Repositories/Other/sample/node_modules/ts-node/dist/index.js:851
            return old(m, filename);
                   ^
Error [ERR_REQUIRE_ESM]: require() of ES Module /home/wheeler/Repositories/Other/sample/node_modules/export-to-csv/output/index.js from /home/wheeler/Repositories/Other/sample/example.ts not supported.
Instead change the require of index.js in /home/wheeler/Repositories/Other/sample/example.ts to a dynamic import() which is available in all CommonJS modules.
    at require.extensions.<computed> [as .js] (/home/wheeler/Repositories/Other/sample/node_modules/ts-node/dist/index.js:851:20)
    at Object.<anonymous> (/home/wheeler/Repositories/Other/sample/example.ts:3:25)
    at m._compile (/home/wheeler/Repositories/Other/sample/node_modules/ts-node/dist/index.js:857:29)
    at require.extensions.<computed> [as .ts] (/home/wheeler/Repositories/Other/sample/node_modules/ts-node/dist/index.js:859:16)
    at phase4 (/home/wheeler/Repositories/Other/sample/node_modules/ts-node/dist/bin.js:466:20)
    at bootstrap (/home/wheeler/Repositories/Other/sample/node_modules/ts-node/dist/bin.js:54:12)
    at main (/home/wheeler/Repositories/Other/sample/node_modules/ts-node/dist/bin.js:33:12)
    at Object.<anonymous> (/home/wheeler/Repositories/Other/sample/node_modules/ts-node/dist/bin.js:579:5) {
  code: 'ERR_REQUIRE_ESM'
}

Desktop (please complete the following information):

  • OS: Fedora 38
  • Browser: n/a
  • Version: n/a

Node.js v18.19.0, ts-node v10.9.2

Using with create-react-app produces "failed to parse source map" warning

After upgrading to CRA v5 I started seeing this warning in my terminal:

Failed to parse source map from '/Users/ben/Code/aftermarket/www/node_modules/export-to-csv/build/export-to-csv.js.map' file: Error: ENOENT: no such file or directory, open '/Users/ben/Code/aftermarket/www/node_modules/export-to-csv/build/export-to-csv.js.map'

Please add a source map to optimize compilation with Webpack.

How can Download data with nexted array?

Hello All,

Can anyone help me to download CSV with Nexted Array?

{

"name" : "rohit",
"email" : "[email protected]",
"phone" : "123",
"activity_array" : [
{
"activity_desc" : "First time Registration",
"activity_title" : "User Registration",
},
{
"activity_desc" : "fadsf\nadsf\nadsf\nsa\nf\nsf\nsdf",
"activity_title" : "reagarding salary",
},
{
"activity_desc" : "adfa",
"activity_title" : "fanl",
}
]
}

Blob is not defined

Hey guys I got this error

ReferenceError: Blob is not defined

What I must to update something?

Thanks

How to keep array as data?

I have an object that looks like

{ project: 'skynet-dev-335306', name: 'pipeline-runner', machineType: 'n1-standard-4', status: 'TERMINATED', zone: 'us-west1-b', diskSizeGb: [ '100', '100' ], diskType: [ 'PERSISTENT', 'PERSISTENT' ] }

But right now
image

Its taking over next column how do I keep it in same column?

Open OS save modal

Hello,

Not so much an issue as a possible feature question, Is there a way or can a way be implemented to allow the developer to leave the file name blank, and allow the user to set it through a save window? similar to the way word saves a document or excel.

If so, let me know as I've implemented this library and may switch out if not a possibility. works well otherwise btw.

Not exporting more than 40 columns

Hi,
I tried this library for my project and it is not exporting more than 40 columns where I have 47 colimns in my table(json). Also it shows the empty field as undefined..

Support different encodings

Currently generated csv file is in UTF-8 or UTF-8 with BOM encoding (default).
This produces problems with determining negative float values when opening in MS Excel. It treats negative values as a text with a dash symbol instead of float value with minus...
When I manually converted file to ASCII encoding - it opens in MS Excel correctly.
So it would be great if I can set file encoding in export-to-csv options

Filename doesn't seem to work in options

Hi, I have the options this way:
const options = {
fieldSeparator: ',',
filename: 'response_time',
quoteStrings: '"',
decimalSeparator: '.',
showLabels: true,
showTitle: false,
title: 'report',
useTextFile: false,
useBom: true,
useKeysAsHeaders: true,
};
const csvExporter = new ExportToCsv(options);
csvExporter.generateCsv(data);

and th file is still downloaded with some random generated file name. Any idea what i might be doing wrong here

NullInjectorError

Hi,

I got his issue :

core.js:6479 ERROR Error: Uncaught (in promise): NullInjectorError: R3InjectorError(AdminpanelModule)[ExportToCsv -> ExportToCsv -> ExportToCsv -> ExportToCsv]:
NullInjectorError: No provider for ExportToCsv!
NullInjectorError: R3InjectorError(AdminpanelModule)[ExportToCsv -> ExportToCsv -> ExportToCsv -> ExportToCsv]:
NullInjectorError: No provider for ExportToCsv!

Kindly, advise

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.