导出图片和表格
import { saveAs } from './'
import Excel from 'exceljs'
const exportToExcel = (data = { columns: [], rows: [], baseImg: '' }, name) => {
if (!data.columns || !data.rows) return
const columns = data.columns
const rows = data.rows
const baseImg = data.baseImg
const workbook = new Excel.Workbook()
const worksheet = workbook.addWorksheet(name)
worksheet.mergeCells('A1:R18')
// (img, 'img')
// 通过 base64 将图像添加到工作簿
const imageId1 = workbook.addImage({
base64: baseImg,
extension: 'jpeg'
})
// 在一定范围内添加图片
// (imageId1, {
// tl: { col: 5, row: 0 },
// ext: { width: 1200, height: 600 }
// })
worksheet.addImage(imageId1, {
tl: { col: 0, row: 0 },
br: { col: 18, row: 18 }
})
worksheet.addTable({
theme: null,
name: 'MyTable',
ref: 'A20',
columns,
rows
})
// 动态计算表头长度
let width = adaptiveWidth(columns)
if (width.length > 0) {
for (let i = 0; i < width.length; i++) {
worksheet.getColumn(width[i].ind).width = width[i].width
}
}
// const fileType = 'application/,application/-excel'
const fileType = 'application/octet-stream'
workbook.xlsx.writeBuffer().then(data => {
const blob = new Blob([data], { type: fileType })
saveAs(blob, name + '.xlsx')
})
}
const adaptiveWidth = (columns) => {
let result = []
for (let i = 0; i < columns.length; i++) {
let str = columns[i].name.length
// 四个字符为标准长度,累计长度倍数增加
if (str > 4) {
let number = Math.floor(str / 4)
let width = 5 * number + 10
result.push({
ind: i + 1,
width
})
}
}
return result
}
export default exportToExcel