1、下载(导出)表格
html
<div>
<el-button type="success" @click="downTemplate">下载模板</el-button>
<a href :download="(fileName ? fileName : '订单') + '.xlsx'" ref="downloadLink" style="display: none;"></a>
</div>
js
(1)、表格:只有表头
downTemplate() {
let link = this.$refs.downloadLink;
let excelData = [["姓名", "年龄"]];
downloadExcel(link, excelData);
}
(2)、表格:表头加内容
let excelData = [["姓名", "年龄"], ['张三', 12], ['王五', 18] ......];
2、导入表格,并读取表格中的数据
html
<div>
<el-button type="primary" @click="uploadFile">
<input ref="file" type="file" @change="handleChange" style="display: none;" />上传文件
</el-button>
</div>
js
// 上传文件
uploadFile() {
this.$refs.file.click();
},
// 上传文件
handleChange(e) {
let that = this;
const files = e.target.files;
if (!files) {
return;
}
readExcelContent(files[0], excelData => {
if (excelData.length) {
console.log(222, excelData);
} else {
that.$message({
message: "文件为空,请重新上传",
type: "error",
center: true
});
}
});
以下 为上面代码中所用到的方法以及插件:
下载(导出)表格:
export const downloadExcel = (link, excelData) => {
const ws = XLSX.utils.aoa_to_sheet(excelData);
const wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, "Sheet1");
const wbout = XLSX.write(wb, {
type: "binary",
bookType: "xlsx"
});
let tmpDown = new Blob([s2ab(wbout)]);
link.href = URL.createObjectURL(tmpDown);
link.click();
setTimeout(function () {
URL.revokeObjectURL(tmpDown);
}, 100);
}
导入表格,并读取表格中的数据:
export const readExcelContent = (file, callback) => {
const fileReader = new FileReader()
fileReader.onload = function(ev) {
try {
const data = ev.target.result
const workbook = XLSX.read(data, { type: 'binary' })
const sheet = workbook.SheetNames[0]
const excelData = XLSX.utils.sheet_to_json(workbook.Sheets[sheet])
callback(excelData)
} catch (e) {
console.log('read excel => ', e)
}
}
fileReader.readAsBinaryString(file)
}
字符串转字符流:
import XLSX from "xlsx";
export function s2ab(s) {
let buf = new ArrayBuffer(s.length)
let view = new Uint8Array(buf)
for (let i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF
return buf
}