相信大家也是开发中遇到导出导入数据的功能,接下来给大家分享自己的小小经验。拿来用就可以。
首先安装 exceljs 包和 file-saver 包
npm install --save exceljs file-saver
要导出的数据
页面代码
<template>
<div>
<div style="float: right;margin: 10px 10px">
<el-button size="mini" icon="el-icon-download" @click="exportExcel" type="primary">导出</el-button>
</div>
<el-table
:data="data"
border
:header-cell-style="{background:'#eef1f6',color:'#6480b6'}"
>
<el-table-column
prop="name"
min-width="180"
align="center"
label="姓名"
/>
<el-table-column
prop="age"
min-width="180"
label="年龄"
align="center"
/>
<el-table-column
prop="Date"
min-width="180"
label="出生年月"
/>
</el-table>
</div>
</template>
<script>
import { exportExcel } from "../../utils/exportExcelUtil";
export default {
name: "LearnOne",
data(){
return{
data:[
{
name:'阿不都沙拉木',
age:25,
Date:'2022-10-27',
sex: '男'
},
{
name:'西热力江',
age:31,
Date:'2022-10-27',
sex: '男'
},
{
name:'阿迪力江',
age:23,
Date:'2022-10-27',
sex: '男'
},
{
name:'迪丽热巴',
age:30,
Date:'2022-10-27',
sex: '女'
},
{
name:'古力娜扎',
age:32,
Date:'2022-10-27',
sex: '女'
}
],
columns:[
{header: '名称',key: 'name',width: 20 },
{header: '年龄',key: 'age',width: 20 },
{header: '出生年月',key: 'Date',width: 20 },
{header: '性别',key: 'sex',width: 20}
]
}
},
methods:{
exportExcel(){
exportExcel(this.data,this.columns,'明星信息')
}
}
}
</script>
下面是自己封装的工具类
const ExcelJS = require('exceljs');
const FileSaver = require('file-saver') ;
export async function exportExcel(allEquipmentData,columns,fileName) {
const wb = new ExcelJS.Workbook();
const Sheet1 = wb.addWorksheet('Sheet1');
let columnsFont = {name: '宋体', size: 16, color: {rgb: "000000"}, bold: true}
Sheet1.views = [
{state: 'frozen', xSplit: 1, ySplit: 1, topLeftCell: 'G10', activeCell: 'A1'}
];
Sheet1.columns = columns
Sheet1.getRow(1).font = columnsFont
for(var i=0;i<allEquipmentData.length;i++){
Sheet1.getRow(i+2).values = allEquipmentData[i]
}
wb.xlsx.writeBuffer().then(buffer => {
FileSaver.saveAs(new Blob([buffer], {type: 'application/octet-stream'}), fileName+`.xlsx`);
})
}
=》给大家额外的惊喜,也就是导出excel文件的同时,给某一列带上下拉框选项值。这个可以利用在导出模板上。
for (var i=2;i<100;i++){
Sheet1.getRow(i).getCell("sex").dataValidation = {
type: 'list',
allowBlank: true,
formulae: ['"男,女,不男不女"']
};
2022-11-9更新内容 :下拉列表值长度出现限制问题
解决方式:从工作簿中获取下拉列表值
const Sheet1 = wb.addWorksheet('Sheet1');
const Sheet2 = wb.addWorksheet('Sheet2');
var data = ['2022年','2023年','2024年','2025年','2026年']
Sheet2.getRow(1).getCell(1).value = "年份"
Sheet2.getRow(1).font = columnsFont
for(let i=0;i<data.length;i++){
Sheet2.getRow(i+2).getCell(1).value = data[i]
}
for (let i=2;i<1000;i++){
Sheet1.getRow(i).getCell("sex").dataValidation = {
type: 'list',
allowBlank: true,
formulae: ['Sheet2!$A$2:$A$'+data.length]
};
}
如果觉得对你有所帮助就点个赞,有什么问题可以在评论区讨论。