React實現將Excel文件轉爲html顯示/轉爲json數據的demo

由SheetJS出品的js-xlsx是一款非常方便的只需要純JS即可讀取和導出excel的工具庫,功能強大,支持格式衆多,支持xls、xlsx、ods(一種OpenOffice專有表格文件格式)等十幾種格式。

github地址 ,進入選擇react
在線Demo

import React, { PureComponent } from 'react';
import { read, utils } from 'xlsx';

/* list of supported file types */
const SheetJSFT = [
  "xlsx", "xlsb", "xlsm", "xls", "xml", "csv", "txt", "ods", "fods", "uos", "sylk", "dif", "dbf", "prn", "qpw", "123", "wb*", "wq*", "html", "htm"
].map(function (x) {
  return "." + x;
}).join(",");

class SheetPage extends PureComponent {
  state = {
    data: [],
    cols: []
  }

  make_cols = (refstr: any) => {
    let o = [], C = utils.decode_range(refstr).e.c + 1;
    for (var i = 0; i < C; ++i) o[i] = { name: utils.encode_col(i), key: i }
    return o;
  };

  onLoadFile = (e: { target: { files: any; }; }) => {
    const files = e.target.files;
    if (files && files[0]) this.handleFile(files[0]);
  }

  handleFile = (file: Blob/*:File*/) => {
    /* Boilerplate to set up FileReader */
    const reader = new FileReader();
    const rABS = !!reader.readAsBinaryString;
    reader.onload = (e) => {
      /* Parse data */
      const bstr = e.target.result;
      const wb = read(bstr, { type: rABS ? 'binary' : 'array' });
      /* Get first worksheet */
      const wsname = wb.SheetNames[0];
      const ws = wb.Sheets[wsname];
      /* Convert array of arrays */
      const data = utils.sheet_to_json(ws, { header: 1 });
      /* Update state */
      this.setState({ data: data, cols: this.make_cols(ws['!ref']) });

    };
    if (rABS) reader.readAsBinaryString(file); else reader.readAsArrayBuffer(file);
  };


  render() {
    console.log(this.state.data)
    return (
      <div>
        <h1>新增頁面</h1>
        <input type="file" onChange={this.onLoadFile} accept={SheetJSFT}/>

        <OutTable data={this.state.data} cols={this.state.cols}/>

      </div>
    );
  }
}

class OutTable extends React.Component {
  render() {
    return (
      <div className="table-responsive">
        <table className="table table-striped">
          <thead>
          <tr>{this.props.cols.map((c) => <th key={c.key}>{c.name}</th>)}</tr>
          </thead>
          <tbody>
          {this.props.data.map((r, i) => <tr key={i}>
            {this.props.cols.map(c => <td key={c.key}>{r[c.key]}</td>)}
          </tr>)}
          </tbody>
        </table>
      </div>
    );
  };
};

export default SheetPage;

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章