安装
//npm install exceljs
npm install exceljs@4.0.0 --save
npm install file-saver
<template>
<button @click="dade66">导出 66</button>
</template>
<script>
import ExcelJS from 'exceljs';
import { saveAs } from 'file-saver';
export default {
data() {
return {
data: [
{ name: '张三', age: 25, gender: '男' },
{ name: '李四', age: 30, gender: '女' },
],
};
},
methods: {
async dade66() {
const workbook = new ExcelJS.Workbook();
const worksheet = workbook.addWorksheet('Sheet1');
// 设置表头
worksheet.columns = [
{ header: '姓名', key: 'name' },
{ header: '年龄', key: 'age' },
{ header: '性别', key: 'gender' },
];
// 添加数据
this.data.forEach(item => {
worksheet.addRow({ name: item.name, age: item.age, gender: item.gender });
});
// 生成 Excel 文件并保存
await workbook.xlsx.writeBuffer().then(buffer => {
const blob = new Blob([buffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
saveAs(blob, 'exported_data.xlsx');
});
},
},
};
</script>
全
<template>
<button @click="dade66">导出 66</button>
</template>
<script>
// npm install exceljs
// npm install file-saver
import ExcelJS from 'exceljs';
import { saveAs } from 'file-saver';
export default {
data() {
return {
data: [
{ name: '张三', age: 25, gender: '男' },
{ name: '李四', age: 30, gender: '女' },
],
};
},
methods: {
async dade66() {
const workbook = new ExcelJS.Workbook();
const worksheet = workbook.addWorksheet('Sheet1');
// 设置表头
worksheet.columns = [
{ header: '姓名', key: 'name' },
{ header: '年龄', key: 'age' },
{ header: '性别', key: 'gender' },
];
// 添加数据
this.data.forEach(item => {
worksheet.addRow({ name: item.name, age: item.age, gender: item.gender });
});
// 冻结表头(第一行)
worksheet.views = [{state: 'frozen',ySplit: 1}];
// 设置列宽
worksheet.getColumn(1).width = 15; // 假设设置第一列(姓名列)宽度为 15
worksheet.getColumn(2).width = 10; // 假设设置第二列(年龄列)宽度为 10
worksheet.getColumn(3).width = 10; // 假设设置第三列(性别列)宽度为 10
// 设置行高
worksheet.getRow(1).height = 18; // 设置第一行(表头行)高度为 25
worksheet.eachRow((row, rowNumber) => {
if (rowNumber > 1) {
row.height = 18; // 设置数据行高度为 20
}
});
// 设置居中对齐
for (let rowNumber = 1; rowNumber <= worksheet.rowCount; rowNumber++) {
const row = worksheet.getRow(rowNumber);
for (let columnNumber = 1; columnNumber <= worksheet.columnCount; columnNumber++) {
const cell = row.getCell(columnNumber);
cell.alignment = { vertical: 'middle', horizontal: 'center' };
}
}
// 合并单元格
worksheet.mergeCells('A5:C5'); // 合并第一行的 A 到 C 列
worksheet.mergeCells('A6:C7'); // 跨行合并
// 生成 Excel 文件并保存
await workbook.xlsx.writeBuffer().then(buffer => {
const blob = new Blob([buffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
saveAs(blob, 'exported_data.xlsx');
});
},
},
};
</script>