使用exceljs和file-saver导出带图片的excel表格
参考
https://www.swvq.com/article/detail/487
https://github.com/exceljs/exceljs/blob/master/README_zh.md#图片
import ExcelJS from 'exceljs'
import fileSaver from 'file-saver'
let workbook = null
let worksheet = null
// 图片转base64
const convertImgToBase64 = (url) => {
return new Promise((resove, reject) => {
const canvas = document.createElement('canvas') as HTMLCanvasElement
const ctx = canvas.getContext('2d')
const img = new Image()
img.crossOrigin = 'Anonymous'
img.onload = function () {
canvas.height = img.height
canvas.width = img.width
ctx.drawImage(img, 0, 0, img.width, img.height)
var dataURL = canvas.toDataURL('image/png')
resove(dataURL)
}
img.src = url
})
}
// 导出
const handleExport = async () => {
workbook = new ExcelJS.Workbook()
workbook.created = new Date()
workbook.modified = new Date()
worksheet = workbook.addWorksheet('sheet-demo')
worksheet.columns = [
{ header: 'skuid', key: 'id', width: 10 },
{ header: '姓名', key: 'name', width: 32 },
{ header: '图片', key: 'DOB', width: 10, outlineLevel: 1 },
]
const row = worksheet.getRow(2)
row.values = [2356545456, 'wb927448', 'https://www.baidu.com']
const data = await convertImgToBase64('https://avatars.githubusercontent.com/u/40457081?s=48&v=4')
console.log(data)
const imageId = workbook.addImage({
base64: data,
extension: 'png',
})
console.log(imageId)
worksheet.addImage(imageId, {
tl: {
col: 3,
row: 5,
},
ext: {
width: 40,
height: 40,
},
// 超链接
hyperlinks: {
hyperlink: 'https://www.baidu.com',
tooltip: 'https://www.baidu.com',
},
})
const buffer = await workbook.xlsx.writeBuffer()
fileSaver(
new Blob([buffer], {
type: 'application/octet-stream',
}),
'demo.xlsx'
)
}