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

后端 未结 3 1309
终归单人心
终归单人心 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:24

    Figured it out. A combination of react-file-reader and HTML5's FileReader (see this page).

    Placed the react-file-reader bit inside of render:

    <ReactFileReader handleFiles={this.handleFiles} fileTypes={'.csv'}>
        <button className='btn'>Upload</button>
    </ReactFileReader>
    

    And then this above.

    handleFiles = files => {
        var reader = new FileReader();
        reader.onload = function(e) {
            // Use reader.result
            alert(reader.result)
        }
        reader.readAsText(files[0]);
    }
    
    0 讨论(0)
  • 2020-12-23 12:31

    The easiest way to upload and read csv files in React (React.js) is react-papaparse ( Home | Demo | Docs | Github ).

    Look at the simply example below:

    import React, { Component } from 'react'
    import { CSVReader } from 'react-papaparse'
    
    const buttonRef = React.createRef()
    
    export default class CSVReader1 extends Component {
      handleOpenDialog = (e) => {
        // Note that the ref is set async, so it might be null at some point
        if (buttonRef.current) {
          buttonRef.current.open(e)
        }
      }
    
      handleOnFileLoad = (data) => {
        console.log('---------------------------')
        console.log(data)
        console.log('---------------------------')
      }
    
      handleOnError = (err, file, inputElem, reason) => {
        console.log(err)
      }
    
      handleOnRemoveFile = (data) => {
        console.log('---------------------------')
        console.log(data)
        console.log('---------------------------')
      }
    
      handleRemoveFile = (e) => {
        // Note that the ref is set async, so it might be null at some point
        if (buttonRef.current) {
          buttonRef.current.removeFile(e)
        }
      }
    
      render() {
        return (
          <>
            <h5>Basic Upload</h5>
            <CSVReader
              ref={buttonRef}
              onFileLoad={this.handleOnFileLoad}
              onError={this.handleOnError}
              noClick
              noDrag
              onRemoveFile={this.handleOnRemoveFile}
            >
              {({ file }) => (
                <aside
                  style={{
                    display: 'flex',
                    flexDirection: 'row',
                    marginBottom: 10
                  }}
                >
                  <button
                    type='button'
                    onClick={this.handleOpenDialog}
                    style={{
                      borderRadius: 0,
                      marginLeft: 0,
                      marginRight: 0,
                      width: '40%',
                      paddingLeft: 0,
                      paddingRight: 0
                    }}
                  >
                    Browe file
                  </button>
                  <div
                    style={{
                      borderWidth: 1,
                      borderStyle: 'solid',
                      borderColor: '#ccc',
                      height: 45,
                      lineHeight: 2.5,
                      marginTop: 5,
                      marginBottom: 5,
                      paddingLeft: 13,
                      paddingTop: 3,
                      width: '60%'
                    }}
                  >
                    {file && file.name}
                  </div>
                  <button
                    style={{
                      borderRadius: 0,
                      marginLeft: 0,
                      marginRight: 0,
                      paddingLeft: 20,
                      paddingRight: 20
                    }}
                    onClick={this.handleRemoveFile}
                  >
                    Remove
                  </button>
                </aside>
              )}
            </CSVReader>
          </>
        )
      }
    }
    
    0 讨论(0)
  • 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 (
          <div className="App">
            <h2>Import CSV File!</h2>
            <input
              className="csv-input"
              type="file"
              ref={input => {
                this.filesInput = input;
              }}
              name="file"
              placeholder={null}
              onChange={this.handleChange}
            />
            <p />
            <button onClick={this.importCSV}> Upload now!</button>
          </div>
        );
      }
    }
    
    export default FileReader;
    
    0 讨论(0)
提交回复
热议问题