将这两个方法融合为一个
时间: 2024-02-09 12:12:29 浏览: 35
可以将获取canvas元素作为图片,插入到xlsx文件并下载的方法封装为一个函数,以便在需要的地方调用。以下是示例代码:
```javascript
import XLSX from 'xlsx'
import { saveAs } from 'file-saver'
function downloadExcelFromCanvas(canvasRef, fileName) {
const canvas = canvasRef.$el
const imgData = canvas.toDataURL('image/png')
const wb = XLSX.utils.book_new()
const ws = XLSX.utils.aoa_to_sheet([['Image'], [imgData]])
XLSX.utils.book_append_sheet(wb, ws, 'Sheet1')
const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'binary' })
const blob = new Blob([s2ab(wbout)], { type: 'application/octet-stream' })
saveAs(blob, fileName)
}
function s2ab(s) {
const buf = new ArrayBuffer(s.length)
const view = new Uint8Array(buf)
for (let i = 0; i < s.length; i++) {
view[i] = s.charCodeAt(i) & 0xff
}
return buf
}
```
使用时,只需要传入canvas元素的引用和文件名即可。例如:
```javascript
<template>
<div>
<canvas ref="canvasRef"></canvas>
<button @click="downloadExcel">下载Excel文件</button>
</div>
</template>
<script>
import { downloadExcelFromCanvas } from '@/utils'
export default {
methods: {
downloadExcel() {
downloadExcelFromCanvas(this.$refs.canvasRef, 'example.xlsx')
}
}
}
</script>
```
在上面的代码中,downloadExcelFromCanvas()函数会生成一个包含canvas元素的图片的xlsx文件,并将该文件下载到本地。注意,需要在函数中使用s2ab()函数将字符串转换为ArrayBuffer类型的数据。
阅读全文