代码
1.导出按钮
<Button
type="primary"
onClick={this.onExportFY}
style={{ marginRight: '60px' }}
>导出excel</Button>
2.导出方法
onExportFY = async() => {
let workbook = new Excel.Workbook();
workbook.creator = 'Web';
workbook.lastModifiedBy = 'Web';
workbook.created = new Date();
workbook.modified = new Date();
workbook.lastPrinted = new Date();
let sheetName = 'sheet名';
let currentData = moment().format("YYYY-MM-DD");
let month = moment().month()+1;
let year = moment().year();
let endYear = year;
let endMonth = month+1;
if(month==12){
endYear = year+1;
endMonth = "01"
}else if (month<9){
month = "0"+month
endMonth ="0"+endMonth
}else if (month=9){
month = "0"+month
}
let startDate = year+"-"+month+"-"+"01";
let endDate = endYear+"-"+endMonth+"-"+"01";
console.log("startDate",startDate,endDate)
let command ={
command: [查询语句]}
let dataSource = await getDocumentsByMongoSql({
collectionName: '数据库名',
serviceName: '微服务名',
command,
pagination:{current:1,pageSize:10000} })
let worksheet = workbook.addWorksheet(sheetName,{views:[{showGridLines:false}]});
console.log('4455',this.props)
let colums = [
{
title: '列名',
dataIndex: 'lieming',
key: 'lieming',
}
]
let formData = [];
let sheetData = dataSource.content;
if(!sheetData||Array.isArray(sheetData)&&sheetData.length==0){
message.warn("无可导出数据")
return
}
console.log('sheetData',sheetData);
formData = sheetData.map((item,index)=>{
let map = {}
for(let col of colums){
let dataIndex = col.dataIndex
let title = col.title
map[title] = item[dataIndex]
return map
})
let columnArr = [];
for(let i in formData[0]){
let tempObj = {name:""};
tempObj.name = i;
columnArr.push(tempObj)
}
let headerName = "RequestsList";
worksheet.addTable({
name:headerName,
ref:"A1",
headerRow: true,
totalsRow: false,
style: {
theme: "TableStyleMedium2",
showRowStripes: false,
width: 200
},
columns: columnArr ? columnArr : [{name:""}],
rows: formData.map((e) => {
let arr = [];
for(let i in e){
arr.push(e[i]);
}
return arr;
})
})
adjustSheetColumnsWidth(worksheet)
worksheet.getRow(0).eachCell(cell => cell.border = excel_border)
workbook.xlsx.writeBuffer().then((data) => {
const blob = new Blob([data], { type: 'xlsx' });
FileSaver.saveAs(blob, `导出数据(${month}月).xlsx`);
});
}
3.调整列宽
export function adjustSheetColumnsWidth(worksheet) {
let lengths = []
worksheet.eachRow(row =>
row.eachCell((cell, index) => {
if (!_.isEqual(cell.font, excel_title_font_style)) {
lengths[index] = Math.max(getByteLength(cell.value), lengths[index] || 0)
}
}))
worksheet.columns = lengths.map(length => ({width: length + 2}))
}
4.引包
import Excel from 'exceljs'
import * as FileSaver from 'file-saver'
|