第一步 安装xlsx
npm install -S file-saver xlsx
第二步 引入xlsx
全局引用(main.js 建议使用场景多时全局引用)
import XLSX from 'xlsx'(适用vue3)
或
import * as XLSX from 'xlsx/xlsx.mjs'(适用vue2)
Vue.prototype.XLSX = XLSX
组件内引用(建议使用场景多时全局引用)
import XLSX from 'xlsx'(适用vue3)
或
import * as XLSX from 'xlsx/xlsx.mjs'(适用vue2)
第三步 导出使用
<Upload action=""
accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
:format="['xls', 'xlsx']"
:before-upload="handleBefore2"
:max-size="2048"
:show-upload-list="false">
<Button type="primary" icon="md-cloud-upload" size="small" class="upload_btn">文件上传</Button>
</Upload>
export default {
props:['apiData'],
data () {
return {
batchImportData: [{ip: 'http://www.baidu.com/'},{ip: 'https://juejin.cn/',}],
}
},
mounted() {
},
methods: {
//下载模版
exportExcel(excelName) {
const data = XLSX.utils.json_to_sheet(this.batchImportData)
const wb = XLSX.utils.book_new()
XLSX.utils.book_append_sheet(wb, data, 'iplist')
// data["A1"]= {
// t: "s",
// v: "ip",//单元格文字
// s: {
// font: {
// name: "宋体",
// sz: 140,
// bold: true,
// color: { rgb: "000" },
// },
// //设置更多样式可参考下图
// alignment: {
// horizontal: "center",
// vertical: "center",
// },
// fill: { bgcolor: { rgb: "ffff00" } },
// }
// }
XLSX.writeFile(wb,'xxxx.xlsx')
},
展示
导入
// 导入之前判断
handleBefore2(file) {
const types = [
"application/vnd.ms-excel",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
];
if (types.indexOf(file.type) === -1) {
this.$Message.warning("不支持的文件类型");
return false;
}
let list = []
this.file2XLSX(file).then((res) => {
console.log(res[0].sheet)//res[0].sheet就是你要的表单数据
res[0].sheet.forEach(item => {
list.push(item.ip)
})
})
return false
},
// excel导入方法
file2XLSX (file) {
return new Promise(function (resolve, reject) {
// 通过FileReader对象读取文件
const reader = new FileReader()
// 读取为二进制字符串
reader.readAsBinaryString(file)
reader.onload = function (e) {
// 获取读取文件成功的结果值
const data = e.target.result
// XLSX.read解析数据,按照type 的类型解析
let wb = XLSX.read(data, {
type: 'binary' // 二进制
})
// 存储获取到的数据
const result = []
// 工作表名称的有序列表
wb.SheetNames.forEach(sheetName => {
result.push({
// 工作表名称
sheetName: sheetName,
// 利用 sheet_to_json 方法将 excel 转成 json 数据
sheet: XLSX.utils.sheet_to_json(wb.Sheets[sheetName])
})
})
resolve(result)
}
})
},