vue插件-前端excel导出的几种方式、导入excel文件
vue插件-前端导出Excel (可导出全量数据)
安装依赖依赖
npm i -s file-saver@2.0.2
npm install -s xlsx@0.15.1
页面下载按钮
<w-button type="success" @click="downLoadAll">下载</w-button>
methods中的方法
// 下载列表所有数据 async downLoadAll () { this.loading = true
let params = { // 参数获取
search: this.form.search,
pageSize = 2000 // 设置获取的数据数量 pageNumber = 1
} try { let requestType = { params: params, headers: {'Content-Type': 'application/json'} } let res = await this.$http(this.$api.getAssListDatas, params, requestType) if (!this.$utils.fetchSuccess(res.data.status)) return let dataThis = res.data.data.rows require.ensure([], () => { const {exportJsonToExcel} = require('@/excel/Export2Excel') const tHeader = ['姓名', '身份证号', '人群分类', '评估日期'] // 设置excel头信息 const filterVal = ['name','idCardNo', 'crowdCategoryName', 'assessDate'] const list = dataThis const data = this.formatJson(filterVal, list) exportJsonToExcel([], tHeader, data, '老年人健康列表', []) }) } catch (err) { console.log(err, 'err') } finally { this.loading = false } }, formatJson (filterVal, jsonData) { return jsonData.map(v => filterVal.map(j => v[j])) }
vue插件-前端导出Excel表格-(当前页面展示的列数据)
安装依赖2个依赖
cnpm install --save xlsx file-saver 组件里头引入 import FileSaver from 'file-saver' import XLSX from 'xlsx'
组件methods里写一个方法
exportExcel () { /* generate workbook object from table */ var wb = XLSX.utils.table_to_book(document.querySelector('#out-table')) //表格的id /* get binary string as output */ var wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array' }) try { FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), 'sheetjs.xlsx') } catch (e) { if (typeof console !== 'undefined') console.log(e, wbout) } return wbout },
vue插件-前端批量打包导出文件(.zip)
安装依赖
npm install -S axios npm install -S jszip npm install -S file-saver 组件里头引入 import JSZip from 'jszip' import fileSaver from 'file-saver' import axios from 'axios'
js中引入方法
export function getFile(url) { return request({ url: url, method: 'get', responseType: 'blob' }) }
组件methods里写一个方法
handleBatchDownload() { const dataFile = this.ftypeList //数据源 const zip = new JSZip() const cache = {} const promises = [] dataFile.forEach(item => { const promise = getFile(item.url).then(data => { // 下载文件, 并存成ArrayBuffer对象 const arr_name = item.url.split('/') const file_name = item.typeName + arr_name[arr_name.length - 1] //文件名称 zip.file(file_name, data, { binary: true }) // 逐个添加文件 cache[file_name] = data }) promises.push(promise) }) Promise.all(promises).then(() => { zip.generateAsync({ type: 'blob' }).then(content => { // 生成二进制流 FileSaver.saveAs(content, this.currentTime + '复工前准备事项.zip') // 利用file-saver保存文件 }) }) },
this.ftypeList格式图
vue插件-前端批量打包导出文件(Excel表格)
安装依赖
npm install xlsx@0.16.0 --s // 高版本使用有问题,用这个版本可以
组件里引入
import XLSX from 'xlsx'
html中
<div class="button-area"> <w-upload class="upload-demo" ref="upload" action="/" :on-change="excelChange" :show-file-list="false" :auto-upload="false"> <w-button slot="trigger" type="primary" >批量导入</w-button> </w-upload> <div><w-button type="warning" >日志查看</w-button></div> </div>
methods里导入方法
// excel 导入 excelChange (file) { this.importData = this.readExcel(file) console.log(this.importData) }, // 解析excel readExcel (file) { const types = file.name.split('.')[1] const fileType = [ 'xlsx', 'xlc', 'xlm', 'xls', 'xlt', 'xlw', 'csv' ].some(item => item === types) if (!fileType) { this.$Message('格式错误!请重新选择') return } this.$emit('showLoading', true) const reader = new FileReader() let result = [] reader.onload = function (e) { const data = e.target.result const wb = XLSX.read(data, { type: 'binary', cellDates: true }) wb.SheetNames.forEach((sheetName) => { result.push({ sheetName: sheetName, sheet: XLSX.utils.sheet_to_json(wb.Sheets[sheetName]) }) }) } reader.readAsBinaryString(file.raw) if (result) { console.log(result) } return result },
// 格式化入参 [处理对应的select值对应转换]
paramsFormate (value, options) {
let newValue = ''
options.forEach((item) => {
if (item.label === value) {
newValue = item.value
}
})
return newValue
},
watch中
watch: { importData: {
// 必填项拦截 async handler (newV, oldV) { if (newV && newV.length > 0) { let keys = Object.keys(newV[0].sheet[0]) if (keys.indexOf('身份证') < 0) { this.$emit('showLoading', false) this.$Message('身份证必填!') return } if (keys.indexOf('采样方式') < 0) { this.$emit('showLoading', false) this.$Message('采样方式必填!') return } if (keys.indexOf('采样时间') < 0) { this.$emit('showLoading', false) this.$Message('采样时间必填!') return } // 表格数据解析 let impdata = newV[0].sheet let importDataArray = JSON.parse(JSON.stringify(impdata) .replace(/身份证/g, 'sfzh').replace(/病人ID/g, 'brid').replace(/姓名/g, 'xm') .replace(/申请单号/g, 'sqdh').replace(/性别/g, 'sex').replace(/采样方式/g, 'cyfs') .replace(/采样时间/g, 'cysj').replace(/作废时间/g, 'zfsj').replace(/采样条码/g, 'tmh') .replace(/发布时间/g, 'fbsj').replace(/核酸参考结果/g, 'jg') .replace(/N基因值/g, 'ngen')) // 参数处理 if (importDataArray) { importDataArray.forEach((item) => { if (item.sex.length > 0) { item.sex = this.paramsFormate(item.sex, this.sexOPtions) } }) } console.log(importDataArray) // 传给后台解析后的数据 let param = { jgdm: this.jgdm, excelItemDtoList: importDataArray } const res = await baseDataApi.queryHistoryCleanRecord(param) if (res.data.data) { if (res.data.data.code === 'F') { this.$emit('showLoading', false) this.rkmxObject.rkmxList = [] if (res.data.data.result) { let showdatatable = res.data.data.result.excelErrorItemDtoList this.$emit('showLoadingError', true, showdatatable) } else { this.$Message(res.data.data.message) } } else { this.rkmxObject.rkmxList = res.data.data.result.wmRkmxVoList this.editIndex = this.rkmxObject.rkmxList.length % this.pageSize this.$emit('showLoading', false) } } } }, deep: true, immediate: true } }
解析出的j'son数据
smile