Vue3+exceljs+file-saver 实现将表格数据中包含图片导出Excel
安装 exceljs
npm install exceljs
安装 file-saver
npm install file-saver
实现
const tableData = [
{
name: '123',
age: 18,
avatorImg: 'data:image/png;base64,..',
}
]
const exportData = async () => {
// 创建一个工作簿
const workbook = new ExcelJS.Workbook()
// 创建工作表
const worksheet = workbook.addWorksheet('My Sheet')
// 设置列头
worksheet.columns = [
{ header: '人员名称', key: 'name', width: 30 },
{ header: '重点人员', key: 'avatorImg', width: 20 },
{ header: '年龄', key: 'age', width: 20 },
]
tableData.forEach((item, index) => {
const rowIndex = index + 2 // Excel 行索引从1开始,且第一行为标题
const row = worksheet.addRow({
name: item.name,
warnTime: item.warnTime,
})
const cellHeight = 140 // 单元格高度,单位是点(1/72 英寸)
row.height = cellHeight
// 添加图片
const imageId = workbook.addImage({
base64: 'data:image/jpeg;base64,' + item.avatorImg,
extension: 'png',
})
// 计算图片应该插入的单元格位置
const imageCell = `A${rowIndex}`
worksheet.addImage(imageId, `${imageCell}:${imageCell}`)
})
// 导出 Excel
const buffer = await workbook.xlsx.writeBuffer()
const blob = new Blob([buffer], {
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
})
saveAs(blob, 'example_with_images.xlsx')
}