vue导出excel文件代码
时间: 2023-09-14 21:11:36 浏览: 112
可以使用第三方库`file-saver.js`和`xlsx`来导出Excel文件,代码如下:
```
import { saveAs } from 'file-saver';
import XLSX from 'xlsx';
// 数据
const data = [
{ name: '张三', age: 20, sex: '男' },
{ name: '李四', age: 22, sex: '女' },
{ name: '王五', age: 25, sex: '男' }
];
// 表头
const header = ['姓名', '年龄', '性别'];
// 数据格式化
const formatData = [header, ...data.map(item => [item.name, item.age, item.sex])];
// workbook
const workbook = XLSX.utils.book_new();
// workSheet
const workSheet = XLSX.utils.aoa_to_sheet(formatData);
// 设置单元格样式
workSheet['!cols'] = [{ wpx: 120 }, { wpx: 80 }, { wpx: 50 }]; // 设置列宽
// 添加 worksheet 到 workbook
XLSX.utils.book_append_sheet(workbook, workSheet, 'Sheet1');
// 导出 Excel
const date = new Date();
const fileName = `导出-${date.getFullYear()}${date.getMonth() + 1}${date.getDate()}_${date.getHours()}${date.getMinutes()}${date.getSeconds()}.xlsx`;
XLSX.writeFile(workbook, fileName, { bookType: 'xlsx' });
//下载 Excel
saveAs(new Blob([s2ab(XLSX.write(workbook, { bookType: 'xlsx', type: 'binary' }))], { type: 'application/octet-stream' }), fileName);
// 加密字符串方法
function s2ab(s) {
var buf = new ArrayBuffer(s.length);
var view = new Uint8Array(buf);
for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
return buf;
}
```
阅读全文