JavaScript 的实现Excel 表格 xls xlsx

参考:https://www.cnblogs.com/powertoolsteam/p/Wijmo_SpreadSheet.html
参考:https://www.grapecity.com.cn/developer/spreadjs/scenarios/collaborate-edits#casestudies

Excel表格展示:https://mp.csdn.net/mp_blog/manage/article?spm=1000.2115.3001.5448

<!DOCTYPE html>
<html>
<head>
  <title>test</title>
</head>
<body>
  <input type="file" id="open-excel" >
  <div class="open"></div>
</body>
</html>

<script src="../jquery.js"></script>
<script src="https://cdn.bootcss.com/xlsx/0.11.9/xlsx.core.min.js"></script>
<script type="text/javascript">
  $(function(){
    $('#open-excel').change(function(e) {
        var files = e.target.files;
        var fileReader = new FileReader();
        fileReader.readAsBinaryString(files[0]); // 以二进制方式打开文件
        fileReader.onload = function(ev) {
            try {
                var data = ev.target.result,
                    workbook = XLSX.read(data, {
                        type: 'binary'
                    }),
                    values = []; // 存储获取到的数据
            } catch (e) {
                console.log('文件类型不正确');
                return;
            }

            // 遍历每张表读取
            for (var sheet in workbook.Sheets) {
                if (workbook.Sheets.hasOwnProperty(sheet)) {
                    // 得到表数据并转成json格式
                    values = values.concat(XLSX.utils.sheet_to_json(workbook.Sheets[sheet]));
                    var html = json2Html(values); // 把获取到的数据添加表格
                    console.log('html',html)
                    $('.open').html(html)
                    break; // 如果只取第一张表,加上这行
                }
            }
        }
    });



    htmlKit = {
      _tags: [], html: [],
      _createAttrs: function (attrs) {
        var attrStr = [];
        for (var key in attrs) {
          if (!attrs.hasOwnProperty(key)) continue;
          attrStr.push(key + "=" + attrs[key] + "")
        }
        return attrStr.join(" ")
      },
      _createTag: function (tag, attrs, isStart) {
        if (isStart) {
          return "<" + tag + " " + this._createAttrs(attrs) + ">"
        } else {
          return "</" + tag + ">"
        }
      },
      start: function (tag, attrs) {
        this._tags.push(tag);
        this.html.push(this._createTag(tag, attrs, true))
      },
      end: function () {
        this.html.push(this._createTag(this._tags.pop(), null, false))
      },
      tag: function (tag, attr, text) {
        this.html.push(this._createTag(tag, attr, true) + text + this._createTag(tag, null, false))
      },
      create: function () {
        return this.html.join("")
      }
    };

    function json2Html(data) {
      console.log('data',data)
      var hk = htmlKit;
      hk.start("table", {"cellpadding": "10","cellspacing":"0", "border": "1"});
      hk.start("thead");
      hk.start("tr");
      hk.end();
      hk.end();
      hk.start("tbody");
      $.each(data,function (k, v) {
          if(k==0){
            hk.start("tr");
            $.each(v, function(key, val) {
              hk.tag("td", null, key)
            });
            hk.end()
          }
          hk.start("tr");
          $.each(v, function(key, val) {
            hk.tag("td", null, val)
          });
          hk.end()
      });
      hk.end();
      hk.end();
      return hk.create()
    }

  })

</script>

vue读取xls或xlsx文件
1.选择一款合适的xls插件,我选择的是xlsx
安装:

npm install xlsx

2.template

<template>
  <div>
    <input type="file"
           ref="upload"
           accept=".xls,.xlsx"
           @change="readExcel"
           />
  </div>
</template>

3.js

<script>
import XLSX from 'xlsx'
export default {
  name: 'Excel',
  data () {
    return {
      outputs: []
    }
  },
  methods: {
    readExcel (e) {
      let that = this
      const files = e.target.files
      if (files.length < 1) {
        return false
      } else if (!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())) {
        this.$toast('上传文件格式不正确,请上传xls或者xlsx格式')
        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] // 取第一张表
          console.log(wsname)
          const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]) // 生成json表格内容
          // const ws1 = XLSX.utils.sheet_to_slk(workbook.Sheets[wsname]) // 输出表格对应位置是什么值
          // const ws2 = XLSX.utils.sheet_to_html(workbook.Sheets[wsname]) // 生成HTML输出
          // const ws3 = XLSX.utils.sheet_to_csv(workbook.Sheets[wsname]) // 生成分隔符分隔值输出
          // const ws4 = XLSX.utils.sheet_to_formulae(workbook.Sheets[wsname]) // 生成公式列表(具有值回退)
          // const ws5 = XLSX.utils.sheet_to_txt(workbook.Sheets[wsname]) // 生成UTF16格式的文本

          that.outputs = [] // 清空接收数据
          
          for (let i = 0; i < ws.length; i++) {
            let sheetData = ws[i] // 对数据自行操作
            that.outputs.push(sheetData)
          }
          
          this.$refs.upload.value = ''
          
        } catch (e) {
          console.log(e)
          return false
        }
      }
      fileReader.readAsBinaryString(files[0])
    }
  }
}
</script>


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

web修理工

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值