How to upload and read CSV files in React.js?

后端 未结 3 1322
终归单人心
终归单人心 2020-12-23 12:16

I would like the user to upload a .csv file, and then have the browser be able to parse the data from that file. I am using ReactJS. How would this work? Thanks.

3条回答
  •  心在旅途
    2020-12-23 12:32

    I would use Papa Parse (https://www.npmjs.com/package/papaparse). And here is an example react component:

    class FileReader extends React.Component {
      constructor() {
        super();
        this.state = {
          csvfile: undefined
        };
        this.updateData = this.updateData.bind(this);
      }
    
      handleChange = event => {
        this.setState({
          csvfile: event.target.files[0]
        });
      };
    
      importCSV = () => {
        const { csvfile } = this.state;
        Papa.parse(csvfile, {
          complete: this.updateData,
          header: true
        });
      };
    
      updateData(result) {
        var data = result.data;
        console.log(data);
      }
    
      render() {
        console.log(this.state.csvfile);
        return (
          

    Import CSV File!

    { this.filesInput = input; }} name="file" placeholder={null} onChange={this.handleChange} />

    ); } } export default FileReader;

提交回复
热议问题