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

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

han32681年前 (2024-08-19)javascript1570

代码如示

    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);

      })
    },


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

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

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

分享给朋友:

相关文章

JS/VUE按钮点击上传文件

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

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

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

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

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

js把base64的数据转换成图片并上传

直接上代码,要点就是把base64转成Blob,添加到FormData传递给后台程序,跟选择图片文件上传时一样的了。//base64图片数据 var dataurl = ...

layer弹层遮罩挡住窗体解决,解决layer弹层遮罩挡住窗体的问题

layer弹层遮罩挡住窗体解决,解决layer弹层遮罩挡住窗体的问题

上代码<div>     <div>这里面某个按钮触发弹层<div>     &...