当前位置:首页 > 经验笔记 > javascript > 正文内容

JS/VUE按钮点击excel上传文件解析文件内容

han32684周前 (08-19)javascript176

代码如示

    import * as XLSX from 'xlsx'; // 导入xlsx库


    importFile() {
      const fileType = ['xlsx', 'xls']
      const inputFile = document.createElement('input')
      inputFile.type = 'file'
      inputFile.style.display = 'none'
      inputFile.accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
      document.body.appendChild(inputFile)
      inputFile.click()

      inputFile.addEventListener('change',  () => {
        const file = inputFile.files[0]
        var testmsg = file.name.substring(file.name.lastIndexOf('.') + 1)

        if (!fileType.includes(testmsg)) {
          this.$message.warning('上传的文件格式只能是,xlsx,xls')
          document.body.removeChild(inputFile)
          return false
        }
        //读取xlsx文件数据转换成js数据

        const reader = new FileReader();
        reader.onload = (e) => {
          const data = e.target.result;
          const workbook = XLSX.read(data, { type: 'binary' });

          // 假设第一个工作表是我们需要的数据
          const firstSheetName = workbook.SheetNames[0];
          const worksheet = workbook.Sheets[firstSheetName];

          // 将工作表转换为JSON
          const json = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
         
          // 处理JSON数据
          console.log('json',json);
          // 这里可以对json进行进一步处理,例如展示在界面上
         
          document.body.removeChild(inputFile); // 清除临时创建的input元素
        };
        reader.onerror = (err) => {
          console.error('Error reading file:', err);
          document.body.removeChild(inputFile);
        };
        reader.readAsBinaryString(file);

      })
    },


扫描二维码推送至手机访问。

版权声明:本文由瀚文博客发布,如需转载请注明出处。

本文链接:http://hanwenblog.com/post/107.html

分享给朋友:

相关文章

树形结构(tree)和扁平数组(list)的相互转换

项目中很多地方需要用到树形结构表格等,因此自己封了个VUE的树和表格组件,需要经常对两种形式的数据进行相互转换,这里记录下转换的方法扁平数组转换为树形结构这个是最常用的,当我们从后台获取一个扁平数组的...

js数组取交集、并集、差集、补集

js数组取交集、并集、差集、补集

一、简单数组let arrA = [1,2,3,4] let arrB = [4,5,6,7] // 取交集 let&nbs...

JS/VUE按钮点击上传文件

直接上代码    importFile() {       const fil...

element UI的表格fixed悬浮固定列错乱的官方解决办法

一般从无数据到有数据, 表格中的fixed列就会出现排版 以及各种奇奇怪怪的情况, 官方的办法是用表格的doLayout方法doLayout对 Table 进行重新布局。当 Table 或其祖先元素由...

判断echart实例是否已经存在,如果不存在,就进行初始化

      var myChart = echarts.getInstanceByDom(chartDom)...

发表评论

访客

看不清,换一张

◎欢迎参与讨论,请在这里发表您的看法和观点。