要实现“保留样式下载React Excel文件”的功能,可以使用以下步骤:
npm install react react-dom xlsx
import React from 'react';
import XLSX from 'xlsx';
class DownloadExcel extends React.Component {
downloadExcel = () => {
// 创建一个工作簿
const wb = XLSX.utils.book_new();
// 创建一个工作表
const ws = XLSX.utils.json_to_sheet(this.props.data);
// 将工作表添加到工作簿
XLSX.utils.book_append_sheet(wb, ws, this.props.sheetName);
// 将工作簿转换为二进制数据
const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
// 将二进制数据转换为Blob对象
const blob = new Blob([wbout], { type: 'application/octet-stream' });
// 创建一个下载链接
const url = URL.createObjectURL(blob);
// 创建一个隐藏的标签,并设置下载链接
const a = document.createElement('a');
a.href = url;
a.download = this.props.fileName;
// 模拟点击下载链接
a.click();
// 释放URL对象
URL.revokeObjectURL(url);
}
render() {
return (
);
}
}
export default DownloadExcel;
import React from 'react';
import DownloadExcel from './DownloadExcel';
class App extends React.Component {
data = [
{ Name: 'John', Age: 30, City: 'New York' },
{ Name: 'Jane', Age: 25, City: 'London' },
{ Name: 'Bob', Age: 35, City: 'Paris' },
];
render() {
return (
);
}
}
export default App;
这样,当用户点击“Download Excel”按钮时,会下载一个名为example.xlsx的Excel文件,其中包含了data数组中的数据,并且保留了样式。
下一篇:保留页面之间的表单数值