vue如何实现纯前端实现导入、导出excel表格

安装依赖(导出)

通过node.js安装:

npm install vue-json-excel

引入:

1、导出表格(list数据不能为空,因为我导出的是模板格式,list就定义啦空,这里list需要你绑定你表格里面的数据)

<html>
<JsonExcel 
:data="list"
 //list:这是你表格中的数据
 :fields="jsonFields" 
//jsonFields:这是你表头的数据
name="美卓标签"
//name:这是你表的标题
 :header="title"
>
              <a-button icon="download">导出模板</a-button>
 </JsonExcel>
</html>
<script>
import JsonExcel from "vue-json-excel";
export default {
  name: 'MzLabelList',
  components: {
    JsonExcel
  },
 data () {
    return {
title:'产品数据',
      jsonFields: {
        '产品编号': 'prodNo',
        '产品重量': 'prWeight',
        '产品含量': 'prContent',
      },
 list: [
        {
          prodNo: '',
          prWeight: '',
          prContent: ''
        }
      ],
}
}
<script>

安装依赖(导入)

通过node.js安装:

npm install xlsx

使用:

<html>
 <span><input type="file" accept=".xls,.xlsx" @change="readExcel($event)" /></span>
</html>
<script>
import XLSX from "xlsx";'
export default {
  name: 'MzLabelList',
 data () {
    return {
list: [],
upload_file: "",
}
},
methods: {
    readExcel (e) {
      // 读取表格文件
      let that = this;
      console.log(e)
      const files = e.target.files;
      if (files.length <= 0) {
        return false;
      } else if (!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())) {
        this.$message({
          message: "上传格式不正确,请上传xls或者xlsx格式",
          type: "warning"
        });
        return false;
      } else {
        // 更新获取文件名
        that.upload_file = files[0].name;
      }
      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表格内容
          // 从解析出来的数据中提取相应的数据
          that.dataSource = []
          ws.forEach(item => {
            that.list.push({
//这里是导入表格的数据,根据自己需要的值截取                
console.log(item)
              prodNo: item.产品编号,
              prWeight: item.产量,
              prContent: item.含量
            });
          });
//假如你需要给push增加后台给的接口,自己增加方法
        } catch (e) {
          return false;
        }
      };
      fileReader.readAsBinaryString(files[0]);
    },
  }
}
<script>

导入数据报'XLSX'错误

就安装一次

npm install xlsx@0.16.0 --save

直接将import XLSX from 'xlsx'改为import * as XLSX from 'xlsx/xlsx.mjs'即可

代码如下:

<html>
 <span><input type="file" accept=".xls,.xlsx" @change="readExcel($event)" /></span>
</html>
<script>
import * as XLSX from 'xlsx'
export default {
  name: 'MzLabelList',
 data () {
    return {
list: [],
upload_file: "",
}
},
methods: {
    readExcel (e) {
      // 读取表格文件
      let that = this;
      console.log(e)
      const files = e.target.files;
      if (files.length <= 0) {
        return false;
      } else if (!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())) {
        this.$message({
          message: "上传格式不正确,请上传xls或者xlsx格式",
          type: "warning"
        });
        return false;
      } else {
        // 更新获取文件名
        that.upload_file = files[0].name;
      }
      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表格内容
          // 从解析出来的数据中提取相应的数据
          that.dataSource = []
          ws.forEach(item => {
            that.list.push({
//这里是导入表格的数据,根据自己需要的值截取                
console.log(item)
              prodNo: item.产品编号,
              prWeight: item.产量,
              prContent: item.含量
            });
          });
//假如你需要给push增加后台给的接口,自己增加方法
        } catch (e) {
          return false;
        }
      };
      fileReader.readAsBinaryString(files[0]);
    },
  }
}
<script>

全部代码如下:

我的是不储存导入数据,实现标签的打印(打印模块后续发)

<template>
  <span>
    <vxe-grid
      ref="xGrid"
      size="mini"
      border
      stripe
      resizable
      keep-source
      async-remove
      row-number
      show-footer
      row-selection
      highlight-hover-row
      highlight-current-row
      :checkbox-config="{ highlight: true, range: true }"
      :height="screenHeight - 100"
      :toolbar="toolbarConfig"
      :columns="tableColumn"
      :data="dataSource"
    >
      <!-- 按钮 -->
      <template v-slot:toolSlot>
        <div>
          <a-space>
            <JsonExcel :data="list" :fields="jsonFields" name="美卓标签">
              <a-button icon="download">导出模板</a-button>
            </JsonExcel>
            <JsonExcel :data="dataSource" :fields="jsonFields" name="美卓标签">
              <a-button :disabled="dataSource.length < 1" icon="download">导出表格</a-button>
            </JsonExcel>
            <span><input type="file" accept=".xls,.xlsx" @change="readExcel($event)" /></span>
            <a-tag color="red" v-if="dataSource.length > 0"> 已导入{{ dataSource.length }}条数据</a-tag>
          </a-space>
        </div>
      </template>
    </vxe-grid>
  </span>
</template>
  
<script>
import JsonExcel from "vue-json-excel";
import * as XLSX from 'xlsx'
export default {
  name: 'MzLabelList',
  components: {
    JsonExcel
  },
  data () {
    return {
      upload_file: "",
      jsonFields: {
        '产品编号': 'prodNo',
        '产品重量': 'prWeight',
        '产品含量': 'prContent',
      },
      list: [
        {
          prodNo: '',
          prWeight: '',
          prContent: ''
        }
      ],
      dataSource: [],
      screenHeight: document.documentElement.clientHeight,
      toolbarConfig: {
        size: 'mini',
        export: true,
        zoom: true,
        refresh: {
          query: this.loadData
        },
        print: true,
        slots: {
          buttons: 'toolSlot',
          text: 'textSuffix'
        },
      },
      tablePage: {
        total: 0,
        currentPage: 1,
        pageSize: 15,
        size: 'mini',
        align: 'right',
        pageSizes: [20, 50, 100, 200],
        perfect: true
      },
      columns: [],
      // 表头
      tableColumn: [
        {
          title: '产品编号',
          align: 'center',
          // sortable: true,
          field: 'prodNo',
        },
        {
          title: '产品重量',
          align: 'center',
          field: 'prWeight'
        },
        {
          title: '产品含量',
          align: 'center',
          field: 'prContent'
        }
      ],
    }
  },
  methods: {
    readExcel (e) {
      // 读取表格文件
      let that = this;
      console.log(e)
      const files = e.target.files;
      if (files.length <= 0) {
        return false;
      } else if (!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())) {
        this.$message({
          message: "上传格式不正确,请上传xls或者xlsx格式",
          type: "warning"
        });
        return false;
      } else {
        // 更新获取文件名
        that.upload_file = files[0].name;
      }
      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表格内容
          // 从解析出来的数据中提取相应的数据
          that.dataSource = []
          ws.forEach(item => {
            that.dataSource.push({
              prodNo: item.产品编号,
              prWeight: item.产量,
              prContent: item.含量
            });
          });
        } catch (e) {
          return false;
        }
      };
      fileReader.readAsBinaryString(files[0]);
    },
  }
}
  </script>
  <style scoped>
@import '~@assets/less/common.less';
</style>
  

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

My&Liu

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

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

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

打赏作者

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

抵扣说明:

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

余额充值