首先下载两个库
- npm install xlsx --save
- npm install file-saver --save
然后在你需要导出的组件里引入库
import { saveAs } from 'file-saver'
import * as XLSX from 'xlsx'
创建函数
const handleExport = () => {
let oneDimensionalArray = []
let twoDimensionalArray = []
let subArrayLength = 5
let data= document.getElementById('xsxl-table').innerText
oneDimensionalArray = data.split('\t').map(item => item.replace(/\n/g, ''))
.map(item => item.replace('编辑删除', ''))
.map(item => item.replace('操作', ''))
for (let i = 0; i < oneDimensionalArray .length; i += subArrayLength) {
twoDimensionalArray.push(oneDimensionalArray .slice(i, i + subArrayLength))
}
console.log(twoDimensionalArray)
// 将数据转换为工作表格式
const ws = XLSX.utils.aoa_to_sheet(twoDimensionalArray)
// 创建一个新的工作簿并添加工作表
const wb = XLSX.utils.book_new()
XLSX.utils.book_append_sheet(wb, ws, "Sheet1")
// 导出工作簿为二进制字符串
const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'array' })
// 使用FileSaver保存文件
saveAs(new Blob([wbout], { type: 'application/octet-stream' }), 'data.xlsx')
}
设置点击事件
<el-form-item @click="handleExport">
导出