由SheetJS出品的js-xlsx是一款非常方便的只需要纯JS即可读取和导出excel的工具库,功能强大,支持格式众多,支持xls、xlsx、ods(一种OpenOffice专有表格文件格式)等十几种格式。
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;