前端js解析excel文件,展示表格数据

使用layui框架

1. upload组件

// html部分
<fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">
  <legend>选完文件后不自动上传</legend>
</fieldset>
 
<div class="layui-btn-container">
  <button type="button" class="layui-btn layui-btn-normal" id="test8">选择文件</button>
  <button type="button" class="layui-btn" id="test9">开始上传</button>
</div>
// JavaScript部分
upload.render({
    elem: '#test8',
    url: '',
    auto: false,
    bindAction: '#test9',
    choose: function(obj) {
        obj.preview((index, file, result) => {
            let workbook = XLSX.read(result.split(';base64,')[1], {type: 'base64', cellDates: true})
            let worksheet = workbook.Sheets[workbook.SheetNames[0]]
        })
    },
    done: function(res){
      layer.msg('上传成功');
      console.log(res)
    }
  });

2.  input#file

// html部分
<input type="file" name="file" id="file" onchange="readFile()">
// JavaScript部分
window.readFile = () => {
  let file = event.target.files[0]
  let reader = new FileReader()
  reader.readAsBinaryString(file)
  reader.onload = (res) => {
    let workbook = XLSX.read(res.target.result, {type: 'binary', cellDates: true}) // 读取excel文件
    let worksheet = workbook.Sheets[workbook.SheetNames[0]] //获取第一个worksheet对象
  }
}

参考资料:

  1. https://github.com/SheetJS/sheetjs
  2. https://www.cnblogs.com/liuxianan/p/js-excel.html
  3. https://www.layui.com/demo/upload.html
  4. https://developer.mozilla.org/zh-CN/docs/Web/API/FileReader
posted @ 2021-09-24 00:13  西伯利亚狼666  阅读(1382)  评论(0)    收藏  举报