7

I am trying to import an excel sheet with multiple columns having different set of data and display it in a react component.

Currently i am doing,

<ReactFileReader handleFiles={this.handleFiles} fileType={'.xlsx'}>
    <button>Import</button>
    </ReactFileReader>

and then

 handleFiles = files =>{
    var fileDisplayArea = this.refs.fileDisplayArea;
    var reader = new FileReader();
    reader.onload = function(e){
    fileDisplayArea.innerHTML = reader.result;
    }
    reader.readAsText(files[0], 'utf-8');
    }

Although this imports the file but when rendered it displays all garbage characters. Any help would be much appreciated.

Thanks,

Vikram

2
  • 2
    You're treating what is essentially a zip archive as though it's a plain text file. That's not going to work: you need to use a library which can parse an xlsx file in a way which can be usefully rendered. Commented Oct 9, 2017 at 19:44
  • @TimWilliams: Makes sense! I guess i should parse it to JSON and then use that output to feed into a reactjs table component. Thanks a lot. Good day! Commented Oct 9, 2017 at 19:53

1 Answer 1

3

react-excel-renderer

There's a perfect library exactly for this ! It converts the excel data to JSON first, then renders it into a HTML table. Its called react-excel-renderer

  • Install it npm install react-excel-renderer --save
  • Import both components ExcelRenderer and OutTable

import {ExcelRenderer, OutTable} from 'react-excel-renderer';

  • Provide the file object to the ExcelRenderer function in your event handler
      fileHandler = (event) => {
    let fileObj = event.target.files[0];

    //just pass the fileObj as parameter
    ExcelRenderer(fileObj, (err, resp) => {
      if(err){
        console.log(err);            
      }
      else{
        this.setState({
          cols: resp.cols,
          rows: resp.rows
        });
      }
    });               
    }
  • Once JSON is obtained, provide it to the OutTable component

<OutTable data={this.state.rows} columns={this.state.cols} tableClassName="ExcelTable2007" tableHeaderRowClass="heading" />

Thats it ! Its done !

A demo for the same can be found here

Sign up to request clarification or add additional context in comments.

2 Comments

I see you wrote the library. Disclosure is appreciated. :)
Hi @Ashish . I have followed your steps, but it's not working for me. see the below post. Thanks

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.