安裝
導(dǎo)入導(dǎo)出excel這是前端做管理系統(tǒng)最常用的功能了,
這里使用到了兩個(gè)組件: file-saver (用于保存文件) xlsx (用于導(dǎo)入導(dǎo)出excel)
npm install -S-D file-saver
npm install -S-D xlsx
2.建立文件
打開你的vue項(xiàng)目镰绎,在src/js文件夾下新建 json2excel.js韩容。
import { saveAs } from 'file-saver'
import XLSX from 'xlsx/dist/xlsx.full.min'
// 將json數(shù)據(jù)處理為xlsx需要的格式
function datenum(v, date1904) {
if (date1904) v += 1462
let epoch = Date.parse(v)
return (epoch - new Date(Date.UTC(1899, 11, 30))) / (24 * 60 * 60 * 1000)
}
function data2ws(data) {
const ws = {}
const range = {s: {c: 10000000, r: 10000000}, e: {c: 0, r: 0}}
for (let R = 0; R != data.length; ++R) {
for (let C = 0; C != data[R].length; ++C) {
if (range.s.r > R) range.s.r = R
if (range.s.c > C) range.s.c = C
if (range.e.r < R) range.e.r = R
if (range.e.c < C) range.e.c = C
const cell = { v: data[R][C] }
if (cell.v == null) continue
const cell_ref = XLSX.utils.encode_cell({c: C, r: R})
if (typeof cell.v === 'number') cell.t = 'n'
else if (typeof cell.v === 'boolean') cell.t = 'b'
else if (cell.v instanceof Date) {
cell.t = 'n'
cell.z = XLSX.SSF._table[14]
cell.v = datenum(cell.v)
}
else cell.t = 's'
ws[cell_ref] = cell
}
}
if (range.s.c < 10000000) ws['!ref'] = XLSX.utils.encode_range(range)
return ws
}
// 導(dǎo)出Excel
function Workbook() {
if (!(this instanceof Workbook)) return new Workbook()
this.SheetNames = []
this.Sheets = {}
}
function s2ab(s) {
const buf = new ArrayBuffer(s.length)
const view = new Uint8Array(buf)
for (let i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF
return buf
}
/*
* th => 表頭
* data => 數(shù)據(jù)
* fileName => 文件名
* fileType => 文件類型
* sheetName => sheet頁(yè)名
*/
export default function toExcel ({th, data, fileName, fileType, sheetName}) {
data.unshift(th)
const wb = new Workbook(), ws = data2ws(data)
sheetName = sheetName || 'sheet1'
wb.SheetNames.push(sheetName)
wb.Sheets[sheetName] = ws
fileType = fileType || 'xlsx'
var wbout = XLSX.write(wb, {bookType: fileType, bookSST: false, type: 'binary'})
fileName = fileName || '列表'
saveAs(new Blob([s2ab(wbout)], {type: "application/octet-stream"}), `${fileName}.${fileType}`)
}
3.使用
1.導(dǎo)出excel
這里有兩種使用方法,一種是加載為組件宵荒,一種是全局加載,我這里因?yàn)榇蟛糠猪?yè)面都需要這個(gè)導(dǎo)出功能,所以我就直接在全局加載了寺谤。
第一步:在main.js中全局掛載toExcel方法
import toExcel from '../src/js/json2excel'
Vue.prototype.$toExcel = toExcel
第二步:創(chuàng)建下載表格的方法即可
//下載表格
downExcel() {
const th = ['文件路徑', '檢測(cè)結(jié)果', '違規(guī)原因', '關(guān)鍵詞'] //創(chuàng)建表頭
const filterVal = ['path', 'conclusion', 'msg', 'words'] //輸出的內(nèi)容
const data = this.dialogData.error.map(v => filterVal.map(k => v[k]))//循環(huán)添加條數(shù)
const [fileName, fileType, sheetName] = ['違規(guī)文件檢測(cè)結(jié)果', 'xlsx', '違規(guī)文件目錄']//文件名稱,后綴吮播,文件內(nèi)的頁(yè)名
this.$toExcel({th, data, fileName, fileType, sheetName})
},
2.讀取excel
此方法應(yīng)該配合一個(gè)file框使用
importfxx(obj) {
//讀取excel
let _this = this;
let inputDOM = this.$refs.upload;
// 通過DOM取文件數(shù)據(jù)
this.file = event.currentTarget.files[0];
var rABS = false; //是否將文件讀取為二進(jìn)制字符串
var f = this.file;
var reader = new FileReader();
//if (!FileReader.prototype.readAsBinaryString) {
FileReader.prototype.readAsBinaryString = function(f) {
var binary = "";
var rABS = false; //是否將文件讀取為二進(jìn)制字符串
var pt = this;
var wb; //讀取完成的數(shù)據(jù)
var outdata;
var reader = new FileReader();
reader.onload = function(e) {
var bytes = new Uint8Array(reader.result);
var length = bytes.byteLength;
for (var i = 0; i < length; i++) {
binary += String.fromCharCode(bytes[i]);
}
//此處引入变屁,用于解析excel
if (rABS) {
wb = XLSX.read(btoa(fixdata(binary)), {
//手動(dòng)轉(zhuǎn)化
type: "base64"
});
} else {
wb = XLSX.read(binary, {
type: "binary"
});
}
//outdata = XLSX.utils.sheet_to_txt(wb.Sheets[wb.SheetNames[1]]);
//console.log("解析的文件內(nèi)容為:" + outdata)
outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[1]]);
//outdata就是讀取的數(shù)據(jù)(不包含標(biāo)題行即表頭,表頭會(huì)作為對(duì)象的下標(biāo))
//此處可對(duì)數(shù)據(jù)進(jìn)行處理
// let arr = [];
// outdata.map(v => {
// let obj = {}
// obj.code = v['Code']
// obj.name = v['Name']
// obj.pro = v['province']
// obj.cit = v['city']
// obj.dis = v['district']
// arr.push(obj)
// });
// _this.da=arr;
// _this.dalen=arr.length;
//把結(jié)果轉(zhuǎn)為json字符串
var jsonstr = JSON.stringify(outdata);
console.log("解析的文件內(nèi)容為:" + jsonstr)
//console.log(jsonstr)
_this.text = jsonstr;
//return arr;
};
reader.readAsArrayBuffer(f);
};
if (rABS) {
reader.readAsArrayBuffer(f);
} else {
reader.readAsBinaryString(f);
}
}