Git Product home page Git Product logo

react-csv's Introduction

Build Status Coverage Status

Build Status Coverage Status

Overview :

Generate a CSV file from given data.

This data can be an array of arrays, an array of literal objects, or strings.

Example :

import { CSVLink, CSVDownload } from "react-csv";

const csvData = [
  ["firstname", "lastname", "email"],
  ["Ahmed", "Tomi", "[email protected]"],
  ["Raed", "Labes", "[email protected]"],
  ["Yezzi", "Min l3b", "[email protected]"]
];
<CSVLink data={csvData}>Download me</CSVLink>;
// or
<CSVDownload data={csvData} target="_blank" />;

For more examples, see here πŸ‘ˆπŸΌ

Install

npm install react-csv --save;

Or for non-node developers, you can use CDN directly:

<script src="https://cdn.rawgit.com/abdennour/react-csv/6424b500/cdn/react-csv-latest.min.js" type="text/javascript"></script>

Components:

This package includes two components: CSVLink and CSVDownload.

0. Common Props:

The two components accept the following Props:

- data Props:

A required property that represents the CSV data. This data can be array of arrays, array of literal objects or string. This can also be a function that returns any of these things.

Example of Array of arrays

// Array of arrays. Each item is rendered as a CSV line
data = [
  ["firstname", "lastname", "email"],
  ["Ahmed", "Tomi", "[email protected]"],
  ["Raed", "Labes", "[email protected]"],
  ["Yezzi", "Min l3b", "[email protected]"]
];

Example of array of literal objects

// Array of literal objects. Each item is rendered as CSV line however the order of fields will be defined by the headers props. If the headers props are not defined, the component will generate headers from each data item.
data = [
  { firstname: "Ahmed", lastname: "Tomi", email: "[email protected]" },
  { firstname: "Raed", lastname: "Labes", email: "[email protected]" },
  { firstname: "Yezzi", lastname: "Min l3b", email: "[email protected]" }
];

Example of strings

// A string can be used if the data is already formatted correctly

data = `firstname,lastname
Ahmed,Tomi
Raed,Labes
Yezzi,Min l3b
`;

// or using 3rd party package
import json2csv from "json2csv";
data = json2csv(arrayOfLiteralObjects);

Example of function returning data

// this function just returns a basic array, but you could also map or return some recently downloaded data in state
function dataFromAsyncProcess() {
  return [
    { firstname: "Ahmed", lastname: "Tomi", email: "[email protected]" },
    { firstname: "Raed", lastname: "Labes", email: "[email protected]" },
    { firstname: "Yezzi", lastname: "Min l3b", email: "[email protected]" }
  ];
}

- headers Props:

Specifying headers helps to define an order of the CSV fields. The csv content will be generated accordingly.

Notes :

  • The meaning of headers with data of type Array is to order fields AND prepend those headers at the top of the CSV content.
  • The meaning of headers with data of type String data is only prepending those headers as the first line of the CSV content.
Custom Header Labels

Custom header labels can be used when converting data of type Object to CSV by having the header array itself be an array of literal objects of the form:

{ label: /* Label to display at the top of the CSV */, key: /* Key to the data */ }

If the header array is an array of strings, the header labels will be the same as the keys used to index the data objects.

Example:

import { CSVLink } from "react-csv";

headers = [
  { label: "First Name", key: "firstname" },
  { label: "Last Name", key: "lastname" },
  { label: "Email", key: "email" }
];

data = [
  { firstname: "Ahmed", lastname: "Tomi", email: "[email protected]" },
  { firstname: "Raed", lastname: "Labes", email: "[email protected]" },
  { firstname: "Yezzi", lastname: "Min l3b", email: "[email protected]" }
];

<CSVLink data={data} headers={headers}>
  Download me
</CSVLink>;
Nested JSON data

It is possible to reference nested strings in your data using dot notation

headers = [
  { label: 'First Name', key: 'details.firstName' },
  { label: 'Last Name', key: 'details.lastName' },
  { label: 'Job', key: 'job' },
];

data = [
  { details: { firstName: 'Ahmed', lastName: 'Tomi' }, job: 'manager'},
  { details: { firstName: 'John', lastName: 'Jones' }, job: 'developer'},
];

Note: if at any point the nested keys passed do not exist then looks for key with dot notation in the object.

- separator Props:

Following a request to add this feature , from 1.0.1 release, react-csv supports separator props which is equals by default a comma , .

import { CSVLink } from "react-csv";

<CSVLink data={array} separator={";"}>
    Download me
</CSVLink>

/*
    "foo";"bar"
    "a";"b"
 */

- enclosingCharacter Props:

Following a request to add this feature, react-csv supports an enclosingCharacter prop which defaults to ".

import {CSVLink} from 'react-csv';

<CSVLink data={array} enclosingCharacter={`'`}>
    Download me
</CSVLink>

/*
    'foo','bar'
    'a','b'
 */

1. CSVLink Component:

It renders a hyperlink and clicking on it will trigger the download action of the CSV document.

It does not accept only data and headers props, but it also renders all props of HTMLAnchor tag. (className, target,....)

- filename Props:

filename is another props restricted to CSVLink. It specifies the filename of the downloaded CSV.

example

import { CSVLink } from "react-csv";

<CSVLink
  data={data}
  filename={"my-file.csv"}
  className="btn btn-primary"
  target="_blank"
>
  Download me
</CSVLink>;

- onClick Props:

onClick is another props restricted to CSVLink.

If it is defined, it means 3 things:

1 - It will run at the top of the click handling logic.

2 - [Sync] If it returns an explicit false, the return will be interpreted as a claim to stop the click handling, then, the next logic will not be executed if so.

3 - [Async] If it is async, "done" argument must be called if you want to invoke the handling of the component. (check examples below)

4 - [Async] If it is async (includes api call, timeout,... ) and it calls done with false will be interpreted as a claim to stop the click handling, then, the next logic will not be executed if so.

examples

  1. πŸ”¬ Sync + Proceed
import { CSVLink } from "react-csv";

<CSVLink
  data={data}
  onClick={() => {
    console.log("You click the link"); // πŸ‘πŸ» Your click handling logic
  }}
>
  Download me
</CSVLink>;
  1. πŸ”¬ Sync + Don't Proceed
import { CSVLink } from "react-csv";

<CSVLink
  data={data}
  onClick={event => {
    console.log("You click the link");
    return false; // πŸ‘πŸ» You are stopping the handling of component
  }}
>
  Download me
</CSVLink>;
  1. πŸ”¬ Async + Proceed
import { CSVLink } from "react-csv";

<CSVLink
  data={data}
  asyncOnClick={true}
  onClick={(event, done) => {
    axios.post("/spy/user").then(() => {
      done(); // REQUIRED to invoke the logic of component
    });
  }}
>
  Download me
</CSVLink>;
  1. πŸ”¬ Async + Don't Proceed
import { CSVLink } from "react-csv";

<CSVLink
  data={data}
  asyncOnClick={true}
  onClick={(event, done) => {
    axios.post("/spy/user").then(() => {
      done(false); // Don't Proceed
    });
  }}
>
  Download me
</CSVLink>;
  • πŸ”¬ Async + data function
import { CSVLink } from "react-csv";

export default class DownloadUserCSVButton extends React.Component {
  constructor(props: {}) {
      super(props);

      this.state = {
        listOfUsers: [],
        loading: false
      };
  }

  getUsers = (event, done) => {
    if(!this.state.loading) {
      this.setState({
        loading: true
      });
      axios.get("/api/users").then((userListJson) => {
        this.setState({
          listOfUsers: userListJson,
          loading: false
        });
        done(true); // Proceed and get data from dataFromListOfUsersState function
      }).catch(() => {
        this.setState({
          loading: false
        });
        done(false);
      });
    }
  }

  dataFromListOfUsersState = () => {
    return this.state.listOfUsers;
  }

  render() {
    const {loading} = this.state;
    return <CSVLink
      data={this.dataFromListOfUsersState}
      asyncOnClick={true}
      onClick={this.getUsers}
    >
      {loading ? 'Loading csv...' : 'Download me'}
    </CSVLink>;
  }
}

2. CSVDownload Component:

It triggers downloading ONLY on mounting the component. so , be careful to render this component whenever it is needed.

It does not accept only data and headers props , but also , it takes advantage of all arguments of window.open function known that its signature is :

window.open(ARG0, target, specs, replace);

Thus, target, specs and replace Props are available .

example

import { CSVDownload } from "react-csv";

<CSVDownload data={data} target="_blank" />;

For non-node developers, they have to use CDN version :

 <script src="https://cdn.rawgit.com/abdennour/react-csv/6424b500/cdn/react-csv-latest.min.js" type="text/javascript"></script>

 <script type="text/babel">
   const {CSVDownload, CSVLink} = ReactCSV;// or window.ReactCSV

   const element= (<CSVDownload data={data} target="_blank" />);

   ReactDOM.render(element, document.querySelector('#app'));
 </script>

Contribution :

  • Unit-tests must cover at least 90% of code .

  • Write documentation of the new class, function, method, attribute ..so on.. following JSDoc syntax.

  • Add an example for the new feature to sample-site.

  • docker-compose run --rm npm start runs the sample-site

  • docker-compose run --rm npm run docgen generates documentation in HTML output.

  • docker-compose run --rm npm run cdn generate a bundle to be used as CDN

Donation

If this project help you reduce time to develop, you can give me a cup of coffee 🍡 :)

paypal

react-csv's People

Contributors

abdennour avatar atefbb avatar blissfuldarkness avatar claytron5000 avatar dajomu avatar dependabot[bot] avatar element-software avatar fcwheat avatar gfpacheco avatar gion avatar gla23 avatar hmudimi avatar iamtekson avatar jimulle avatar khumphrey avatar larrybotha avatar lucianbuzzo avatar maniarab avatar marrouchi avatar matzeso avatar mccabemj avatar mriccid avatar nandotheessen avatar olek-pastukhov avatar quintezkiller avatar rgoyal1405 avatar rolandkutka avatar tegranjeet avatar tomekmularczyk avatar ttrzeng 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-csv's Issues

Loading data asynchronously

Currently the data needs to be passed immediately to the component.

Is there a way to load data asynchronously?

Configuration

Hi, great work @abdennour

It would be great, if you can config the csv, for example, can change the separator, I need it would be a semi-colon (;), to then open in excel.

Umlauts and other special characters not showing in EXCEL

If I export something with umlauts 'ΓΆΓΌΓ€' then Excel does not understand it.

I am unsure where this problem is coming from. Excel cannot read UTF8 properly, but it can read UTF16. Would this mean that react-csv should convert to UTF-16?

!important is not working on style attribute

This line that uses the !important command
<CSVLink data={data} style={{ color : "#ffffff !important"}}>Export to CSV

is rendered as
Export to CSV

I also tried with the prettyLink example

Add a License

Please add a license to this repository so consumers understand how to attribute and distribute this code in the future.

Can't change filename in CSVDownload

Trying to set another name to file with headers
<CSVDownload headers={['Content-Disposition: attachment; filename="filename.csv"']} data={data} />

It does'n work.

Is there a way to change the name in CSVDownload?

Allowing numerical 0 entries

I noticed that exports on objects including the numerical value 0 would have the 0's converted to ""

I identified the line of code that's causing this. https://github.com/abdennour/react-csv/blob/master/src/core.js#L18

The boolean check is going to cast the numerical 0 to false.NaN, false, null, & undefined are also falsy - I could see how not allowing them could lead to confusion.

Currently, the string "0" on objects would not get cast. Also, an array of any values will pass into the CSV without being cast.

What is the expected behavior? I'm willing to open a pull-request with the expected behavior - provided it allows for numerical 0's to be passed in on objects.

Error on first header column name

First of all, thank you for your work!
However, I got an issue using your lib : when I export data, I got a comma before first header element...
const dataTest = [{name:"xxxxxx",firstName:"xxxxxx",email:"[email protected]"},{name:"xxxxxx",firstName:"xxxxxx",email:"[email protected]"}];

In the exported file, I have :

,"name"

as column name.

Using the link with :
<CSVLink data={dataTest} filename={"export.csv"} className="btn btn-primary" target="_blank" separator={";"}> export </CSVLink>

If you could help me with it it would be great!
Thanks in advance

Remove src/ from .npmignore and add jsnext:main to package.json

By removing src/ from .npmignore and adding a jsnext:main field in package.json pointing at src/index.js, you'd enable Webpack 2 (and others) to perform tree shaking. If someone uses only CSVLink, the bits for CSVDownload would not be included in the final bundle.

Component worked earlier in Chrome and now it fails

I had this component working earlier and now anytime I click the CSVLink it fails in Chrome. The same Download: Failed - Network Error.

I have stripped the code back to the basic: Download Report and that fails as well.

Export Button

Hi,

How can have a button which onClick exports the CSV?

Number of rows

How many rows can this hold?

I tried 2000 rows and it didn't work. 1000 rows works though.

When I try to download 2000, I get an empty file.

Set a filename when using CSVDownload

The filename prop allows to set a custom filename to the CSV file, however it's available only when using the CSVLink component. Would be interesting to be able set a filename when using the CSVDownload component as well.

How to escape quotation marks in headers?

Say, I have this headers array:

let headers = ['Header 1', 'Header 2', 'Header "With Quotes" 3', 'Header 4'];

The third header's quotes will not be escaped, and the output will be:

"Header 1","Header 2","Header "With Quotes" 3","Header 4"

Whereas the expected output is:

"Header 1","Header 2","Header ""With Quotes"" 3","Header 4"

Reference: RFC-4180, 2.7:

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"

Is this feature implemented, and, if yes, how to use it?

CSVDownload is not working for me

Hi , i try to use component CSVDownload and it's not working ,example file name ex. 8b062391-5251-425e-9119-8ed46f2307c8 , aaabceb7-2a23-4b39-8b50-d183fba9f4b7

Thank you,for help.

Alternative data and accessor definitions

Greetings and thank you for this library.

My suggestion is based on another library tannerlinsley/react-table.

My need is to customize the headers and values based on similar config of columns.

In react-table library I am able to define every column, their headers and accessors.

{ header: 'Custom Title', accessor: 'field' }
or
{ header: 'Custom Title', render: (row) => row.field }

This way it becomes easy to create visually better exports. Otherwise, I need to reformat all the data and run 10k lines again to visually format what I actually want to export.

i.e. for a date field, I want the title to be 'Example Date' and the value to be formatted as dd.MM.yyyy HH:mm:ss but for json and array outputs I need to evaluate every single row in every report I want to export.

After defining headers the whole column values deleted

Hey !
I add the const:
const headers=["CUSTOM", "NOT CUSTOM", "NOT CUSTOM" ..... ]
By custom i mean different then the json key name, and not custom is exectly as the key name.
later i assigned it into the headers prop
<CSVLink data={this.props.orders} headers={headers} filename={this.state.orderExportFileName + ".csv"}>
And in the export the custom headers column values was blank.
How i can set custom headers?

Remove `.babelrc` file from published npm package

Hey there!
First of all - thank you for this awesome package! πŸ‘
For the past two days, I've been struggling to get react-csv acting nicely with our project. More specifically, npm installs were throwing out error messages.
Finally, I figured out that you include your sample .babelrc file in your npm package, causing babel loader to adapt it. πŸ˜†

TypeError when including library in a test

I get this when including component in a test.
Using WebPack, Karma and PhantomJS.

TypeError: undefined is not a function (evaluating 'Object.assign(_metaProps.defaultProps, defaultProps)')
  at /usr/src/app/tests/test-bundler.js:136375 <- webpack:///~/react-csv/lib/components/Download.js:74:0

Unable to use with Webpack

Hello! I was trying to use your library with webpack but I get this warning:

Warning in ./~/react-csv/index.js
Critical dependencies:
1:17-32 the request of a dependency is an expression
 @ ./~/react-csv/index.js 1:17-32

which led to this error in the browser:

Uncaught Error: Cannot find module 'lib/'.

If I manually change index.js from this:

module.exports = require(`lib`);

to this:

module.exports = require(`./lib/index`);

it seems to work fine!

Related: it seems that x-object, which is a depdency of react-csv, is not compiled with babel, so it gives error when I try to minify my bundle with uglifyjs:

SyntaxError: Unexpected token: operator (>) [./~/x-object/safe.js:2,0]

Do you think that these problems could be fixed? Thank you.

File not being download on click

Hi, I found that the only way to download the file is to right click and do "save file as.."
If I click (either in your demo) a new tab it's openened and closed without the file being downloaded.
I'm testing this with latest chrome on Mac.

Support for desktop app

This is not a bug but a request for enhancement.

This package is really easy to use and powerful. But there is only option to Download CSV file or Open it in new tab.

I am using Electron with React to create awesome desktop applications. There I need to write a file in some directory e.g. D:/myApp/. So, in short I don't want to Download or Open the csv file, instead I want to create a new csv file at the specified location in the client's pc.

Will you please tell that if you like this idea or you wont support it?

'CSVDownload' is defined but never used

Hello! Thanks you for developing such a great component!

I get this warning, because I only uses CSVLink, but if I remove CSVDownload in the import statment it does not work. Isn't it better you insert CSVDownload comp into CSVLink instead so it is not need to have as an import statement?

Fix React.PropTypes to PropTypes.

Recent changes in React makes metaProps.js cause a error/warning.
Suggestion to replace React.PropTypes to PropTypes trough importing separate React npm module 'prop-types'

metaprops
@abdennour

IE Object.assign issue

You are not using any polyfill for Object.assign so this library is not working in IE

Elements with commas not supported

When downloading a file where one of the elements may contain a comma, the file is downloaded incorrectly unless a custom separator is provided that is not a comma. The problem with this is that the file would no longer be a CSV.

I believe the problem would be resolved by updating your joiner() function in src/core.js to be:
export const joiner = ((data,separator = ',') => data.map((row, index) => row.map((element) => "'" + element + "'").join(separator)).join(\n) );

Can't get it works with react-boilerplate

Hi,

i'm trying to add this module to a react-boilerplate based app, but i get this error:

Error: Module parse failed: /Users/silviarosa/Work/htdocs/valentino.webcompiler/node_modules/react-csv/src/components/Download.js Unexpected token (16:22)
You may need an appropriate loader to handle this file type.
| class CSVDownload extends React.Component {
| 
|   static defaultProps = Object.assign(
|     commonDefaultProps,
|     defaultProps

Any idea on how to fix this?

Problem with jsnext:main in package.json

Hi, I got a problem with the jsnext:main field.When I use webpack dev tool β€˜eval’ to start a devserver,this field will point to src/index.js,but it can not pass the eslint rules. The eslint and babel configuration just like below:
"babel": {
"presets": [
[
"env",
{
"es2015": {
"modules": false
}
}
],
"react",
"stage-0"
],
"env": {
"production": {
"only": [
"app"
],
"plugins": [
"transform-decorators-legacy",
"transform-react-remove-prop-types",
"transform-react-constant-elements",
"transform-react-inline-elements"
]
},
"test": {
"plugins": [
"transform-es2015-modules-commonjs",
"dynamic-import-node"
]
}
},
"plugins": [
"transform-decorators-legacy", [
"import",
{
"libraryName": "antd",
"style": "css"
}
]
]
},
"postcss": {
"plugins": []
},
"eslintConfig": {
"parser": "babel-eslint",
"extends": "airbnb",
"env": {
"browser": true,
"node": true,
"jest": true,
"es6": true
},
"plugins": [
"react"
],
"globals": {
"Highcharts": true,
"_config": true
},
"parserOptions": {
"ecmaVersion": 6,
"sourceType": "module",
"ecmaFeatures": {
"jsx": true
}
},
"rules": {
"no-param-reassign": 0,
"prefer-const": 0,
"import/newline-after-import": 0,
"import/no-extraneous-dependencies": 0,
"import/no-dynamic-require": 0,
"import/no-named-as-default": 0,
"import/no-webpack-loader-syntax": 0,
"import/prefer-default-export": 0,
"jsx-a11y/no-static-element-interactions": 0,
"no-underscore-dangle": 0,
"object-curly-spacing": 0,
"react/forbid-prop-types": 0,
"react/prefer-stateless-function": 0,
"react/prop-types": 1,
"react/jsx-filename-extension": [
1,
{
"extensions": [
".js",
".jsx"
]
}
]
},
"settings": {
"import/resolver": {
"webpack": {
"config": "./internals/webpack/webpack.prod.babel.js"
}
}
}
}

but when i delete the jsnext:main field or change if to 'lib/index.js', it's fine.So plz help me to find the solution of use this in devtool of Webpack 2. Thx.

Support utf-8 for IE

I need support Chinese, but IE browser can't see right word.
I use below to work OK. Need a new release, thanks.

handleLegacy(evt, data, headers, separator, filename) {
// If this browser is IE 11, it does not support the `download` attribute

  if (window.navigator.msSaveOrOpenBlob) {
    // Stop the click propagation
    evt.preventDefault()

    //let blob = new Blob([toCSV(data, headers, separator)])
    let blob = new Blob(['\uFEFF', toCSV(data, headers, separator)])
    window.navigator.msSaveBlob(blob, filename)

    return false
  }
}

Custom headers don't work as defined in docs

I'm trying to us an array of objects as my data, and an array of objects to define custom headers. I'm doing this based on the example provided in the README, which doesn't seem to work (see bottom of this comment).


If I do not define custom headers, the data displays correctly with the original headers.

data = [
  {columnA: '1 - Test Data A', columnB: '1 - Test Data B' , columnC: '1 - Test Data C'},
  {columnA: '2 - Test Data A', columnB: '2 - Test Data B' , columnC: '2 - Test Data C'},
  {columnA: '3 - Test Data A', columnB: '3 - Test Data B' , columnC: '3 - Test Data C'}
];

Result:

"columnA","columnB","columnC"
"1 - Test Data A","1 - Test Data B","1 - Test Data C"
"2 - Test Data A","2 - Test Data B","2 - Test Data C"
"3 - Test Data A","3 - Test Data B","3 - Test Data C"

If I try to use custom headers via an array of objects, my data returned blank, and the headers are all returned as [object Object]. (This is the example in the README).

headers = [
  {label: 'columnA', key: 'Column A'},
  {label: 'columnB', key: 'Column B'},
  {label: 'columnC', key: 'Column C'}
];

data = [
  {columnA: '1 - Test Data A', columnB: '1 - Test Data B' , columnC: '1 - Test Data C'},
  {columnA: '2 - Test Data A', columnB: '2 - Test Data B' , columnC: '2 - Test Data C'},
  {columnA: '3 - Test Data A', columnB: '3 - Test Data B' , columnC: '3 - Test Data C'}
];

Result:

"[object Object]","[object Object]","[object Object]"
"","","","","","","",""
"","","","","","","",""

If I try to use custom headers via an array of strings, my headers display correctly, but no data is displayed.

headers = ['Column A', 'Column B', 'Column C'];

data = [
  {columnA: '1 - Test Data A', columnB: '1 - Test Data B' , columnC: '1 - Test Data C'},
  {columnA: '2 - Test Data A', columnB: '2 - Test Data B' , columnC: '2 - Test Data C'},
  {columnA: '3 - Test Data A', columnB: '3 - Test Data B' , columnC: '3 - Test Data C'}
];

Result:

"Column A","Column B","Column C"
"","","","","","","",""
"","","","","","","",""

From the README:

headers = [
  {label: 'First Name', key: 'firstname'},
  {label: 'Last Name', key: 'lastname'},
  {label: 'Email', key: 'email'},
];

data = [
  {firstname: 'Ahmed', lastname: 'Tomi' , email: '[email protected]'},
  {firstname:'Raed', lastname:'Labes' , email:'[email protected]'} ,
  {firstname:'Yezzi', lastname:'Min l3b', email:'[email protected]'}
];

<CSVLink data={data} headers={headers}>
    Download me
</CSVLink>

And this is the result:

"[object Object]","[object Object]","[object Object]"
"","",""
"","",""
"","",""

First fetch data from server then download csv data with same click

First I want to fetch data with API then that data should download with react-csv.
For this, I want to use single button for both work.

this time, I'm using like this -
<Button onClick={this.fetchData}>Fetch Data</Button>

fetchData() {
  axios.get('api_link')
    .then(({data}) => {
      this.setState({data})
    })
}

and then Download data -

<CSVLink
	data={this.state.data}
	headers={this.state.headers}
	filename='AllContent.csv'
	target='_self'
>
	Download me
</CSVLink>

but Buttons will show 2 times. it's not good looking for users.

So, How can I fetch and download data with only one click ?

Unable to download CSV in Microsoft edge

If I try to download CSV on edge browser, it does nothing. Either browser crashes or just opens a new blank tab in few edge versions. Can you please fix this issue for us. Thanks.

Add a title to a sheet

Hi,

I'd like to be able to generate a CSV with my columns and values, but I'd like to set a title header, something that would be centered on the first row and colspanned to the size of the actual columns.

In my case, I'm exporting charts to CSV. So it outputs the datatable of the chart, which is fine. But there are several charts and with the data only, it's sometimes hard to understand what the sheet is about. Say I apply a filter (let's say "date") to my "Distinct visitors by Country" chart and then export it, I'd like it to output something like that:

react-csv-feature

Of course, the filename could be enough, but we don't always only want to rely on that.

Do you think this could be an interesting enhancement? I could look into it and open a PR.

Failed-Network Error while downloading larger data

In the data property, am setting up array of big data size of around 16995 items. Where each array item is having around 16 properties/attributes. I am setting the component as shown below:
<CSVLink
data={this.state.myData}
filename="download.csv"
className="text-white"
style={{'textDecoration': 'none'}}
target="_blank" />

here this.state.myData is having 16995 items and each item is holding around 16 properties.

Kindly suggest!

Select Encoding

I couldn't find in documentation where to define the encoding. My browser is exporting in ASCII-8BIT instead of UTF-8.

Output has non-printable chars

When i export a csv file i get 3 unprintable chars in the beginning of the file - hex values are ef, bb and bf. Am using chrome Version 57.0.2987.133 (64-bit) on OSX. I am using react-csv version 1.0.8
I notice in core.js the following function

var buildURI = exports.buildURI = function buildURI(data, headers, separator) {
  return encodeURI('data:text/csv;charset=utf-8,\uFEFF' + toCSV(data, headers, separator));
};

If i remove the \uFEFF, as given below then the output is as expected without the non-printable chars.

var buildURI = exports.buildURI = function buildURI(data, headers, separator) {
  return encodeURI('data:text/csv;charset=utf-8,' + toCSV(data, headers, separator));
};

Not sure what the issue is.

can't use chinese in datasource

const dataSource = [{
key: '1',
name: "ε†°ε†°",
age: 32,
address: "胑θΏͺ"
}, {
key: '2',
name:"ε†°ε†°",
age: 42,
address: "胑θΏͺ"
}];

const columns = [{
title: '姓名',
dataIndex: 'name',
key: 'name',
}, {
title: 'εΉ΄ιΎ„',
dataIndex: 'age',
key: 'age',
}, {
title: '住址',
dataIndex: 'address',
key: 'address',
}];
This is my datasource.
data

it does not support chinese?

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.