我按照这个教程将数据从数据库导出到excel,我需要添加一些css样式,因为我需要将 "Date "字体加粗和一些标题宽度。
创建数据
//export to excel
const [data, setData] = React.useState([])
const customHeadings = testsList.map(item => {
return ({
"Date": item.date
})
})
React.useEffect(() => {
setData(customHeadings)
}, [])
导出按钮
import { ExportToExcel } from "./ExportToExcel.js"
<ExportToExcel apiData={data} fileName="export_testu" classb="btn btn-default" button="Export testů" />
导出到Excel.js
import React from 'react'
import * as FileSaver from "file-saver";
import * as XLSX from "xlsx";
export const ExportToExcel = ({ apiData, fileName, button, classb }) => {
const fileType =
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8";
const fileExtension = ".xlsx";
const exportToCSV = (apiData, fileName) => {
const ws = XLSX.utils.json_to_sheet(apiData);
const wb = { Sheets: { data: ws }, SheetNames: ["data"] };
const excelBuffer = XLSX.write(wb, { bookType: "xlsx", type: "array" });
const data = new Blob([excelBuffer], { type: fileType });
FileSaver.saveAs(data, fileName + fileExtension);
};
return (
<button onClick={(e) => exportToCSV(apiData, fileName)} className={classb}>{button}</button>
);
};