Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing data from excel and displaying in a react component

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

like image 968
Vikram Mahishi Avatar asked Oct 09 '17 19:10

Vikram Mahishi


People also ask

How do you convert excel to JSON in react?

Hello everyone, in this post we will look at how to solve the React Convert Excel To Json problem in the programming language. import React, { useState } from "react"; import "./App. css"; import * as XLSX from "xlsx"; class ExcelToJson extends React. Component { constructor(props) { super(props); this.


1 Answers

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

like image 57
Ashish Deshpande Avatar answered Oct 22 '22 01:10

Ashish Deshpande