📅  最后修改于: 2023-12-03 14:53:55.197000             🧑  作者: Mango
在React.js中,可以使用React-Bootstrap来构建表格,使用React-Export-Excel将表格转换为Excel文件。以下是具体步骤:
npm install react-bootstrap react-export-excel
import React, { Component } from 'react';
import { Table } from 'react-bootstrap';
import ReactExport from 'react-export-excel';
class TableComponent extends Component {
render() {
return (
<Table striped bordered hover>
<thead>
<tr>
<th>#</th>
<th>First Name</th>
<th>Last Name</th>
<th>Username</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Mark</td>
<td>Otto</td>
<td>@mdo</td>
</tr>
<tr>
<td>2</td>
<td>Jacob</td>
<td>Thornton</td>
<td>@fat</td>
</tr>
</tbody>
</Table>
);
}
}
const ExcelFile = ReactExport.ExcelFile;
const ExcelSheet = ReactExport.ExcelFile.ExcelSheet;
const ExcelColumn = ReactExport.ExcelFile.ExcelColumn;
class ExportExcel extends Component {
render() {
return (
<ExcelFile element={<Button variant="primary">Export to Excel</Button>}>
<ExcelSheet data={[...]} name="Employees">
<ExcelColumn label=" First Name" value="firstName" />
<ExcelColumn label="Last Name" value="lastName" />
<ExcelColumn label="Email" value="email" />
</ExcelSheet>
</ExcelFile>
);
}
}
在ExportExcel组件中,使用React-Export-Excel库将表格转换为Excel文件。
class ExportExcel extends Component {
render() {
return (
<ExcelFile element={<Button variant="primary">Export to Excel</Button>}>
<ExcelSheet data={[...]} name="Employees">
<ExcelColumn label=" First Name" value="firstName" />
<ExcelColumn label="Last Name" value="lastName" />
<ExcelColumn label="Email" value="email" />
</ExcelSheet>
</ExcelFile>
);
}
}
现在,我们可以将表格和ExportExcel组件结合起来。
class TableWithExportExcel extends Component {
render() {
return (
<>
<TableComponent />
<ExportExcel />
</>
);
}
}
现在,我们已经将表格转换为Excel文件,用户可以将数据导出到Excel文件中。
完整代码示例:
import React, { Component } from 'react';
import { Table, Button } from 'react-bootstrap';
import ReactExport from 'react-export-excel';
const ExcelFile = ReactExport.ExcelFile;
const ExcelSheet = ReactExport.ExcelFile.ExcelSheet;
const ExcelColumn = ReactExport.ExcelFile.ExcelColumn;
class TableComponent extends Component {
render() {
return (
<Table striped bordered hover>
<thead>
<tr>
<th>#</th>
<th>First Name</th>
<th>Last Name</th>
<th>Username</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Mark</td>
<td>Otto</td>
<td>@mdo</td>
</tr>
<tr>
<td>2</td>
<td>Jacob</td>
<td>Thornton</td>
<td>@fat</td>
</tr>
</tbody>
</Table>
);
}
}
class ExportExcel extends Component {
render() {
return (
<ExcelFile element={<Button variant="primary">Export to Excel</Button>}>
<ExcelSheet data={[...]} name="Employees">
<ExcelColumn label=" First Name" value="firstName" />
<ExcelColumn label="Last Name" value="lastName" />
<ExcelColumn label="Email" value="email" />
</ExcelSheet>
</ExcelFile>
);
}
}
class TableWithExportExcel extends Component {
render() {
return (
<>
<TableComponent />
<ExportExcel />
</>
);
}
}
export default TableWithExportExcel;