由SheetJS出品的js-xlsx是一款非常方便的只需要纯JS即可读取和导出excel的工具库,功能强大,支持格式众多,支持xls、xlsx、ods(一种OpenOffice专有表格文件格式)等十几种格式。
github地址 ,进入选择react
在线Demo
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 | 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; |