js读取excel,xlsx,xls 表格,转成JSON数据
- 使用 js-xlsx 插件:https://github.com/SheetJS/js-xlsx
- 转为JSON数据后的效果图 欢迎参考
使用 js-xlsx 插件:https://github.com/SheetJS/js-xlsx
HTML内容
创建input type为file 文件上传格式 绑定change事件 通过change事件获取到上传文件的内容
JS内容
<script>
import XLSX from 'xlsx';
export default {data() {return {控制上方弹窗是否显示dialogVisible:false,// 进度条JinDu:0};},
这里是监视dialogVisible发生变化调用methods内声明的QingKong方法watch:{dialogVisible(){if(this.dialogVisible==false){this.QingKong()}}}methods: {这里是防止用户上传文件后改动文件内容再次点击上传不触发change事件做的清空事件QingKong(){this.$refs.readFile.value = '';this.JinDu=0;},这里是解析xls xlsx表格内容转为JSON格式readFile(e) {const files = e.target.files;//如果没有文件名if(files.length<=0){return false;}else if(!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())){console.log('文件传格式不正确');return false;}const fileReader = new FileReader();fileReader.onload = (ev) => {try {const data = ev.target.result;const workbook = XLSX.read(data, {type: 'binary'});const wsname = workbook.SheetNames[0];//取第一张表const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]);//生成json表格内容// console.log('JOSN转化结果:',ws);for(let i = 0; i < ws.length; i ++) {ws[i].出生年月 = this.formatDate(ws[i].出生年月, '-')this.JinDu=Math.round(i / ws.length *100);// console.log(this.JinDu);}console.log(ws)} catch (e) {return false;}};fileReader.readAsBinaryString(files[0]);},这里是日期转换方formatDate(numb, format) {const time = new Date((numb - 1) * 24 * 3600000 + 1)time.setYear(time.getFullYear() - 70)const year = time.getFullYear() + ''const month = time.getMonth() + 1 + ''const date = time.getDate() - 1 + ''if (format && format.length === 1) {return year + format + (month < 10 ? '0' + month : month) + format + (date < 10 ? '0' + date : date)}return year + (month < 10 ? '0' + month : month) + (date < 10 ? '0' + date : date)},};
</script>