vue项目:使用xlsx导出Excel数据


一、安装xlsx

执行命令:npm i xlsx file-saver --save
在这里插入图片描述

二、报错及解决

使用时:import XLSX from "xlsx"; 发现如下报错信息
在这里插入图片描述
报错原因:xlsx版本不兼容。

解决也很简单:
1)先移除已安装的xlsx: npm uninstall xlsx
2)安装低版本:npm i xlsx@0.17.0

三、编写公共方法

// exportExcel.js
import { saveAs } from "file-saver";
import XLSX from "xlsx";

function datenum(v, date1904) {
  if (date1904) v += 1462;
  const epoch = Date.parse(v);
  return (epoch - new Date(Date.UTC(1899, 11, 30))) / (24 * 60 * 60 * 1000);
}

function sheet_from_array_of_arrays(data) {
  let ws = {};
  let range = {
    s: {
      c: 10000000,
      r: 10000000
    },
    e: {
      c: 0,
      r: 0
    }
  };
  for (let R = 0; R != data.length; ++R) {
    for (let C = 0; C != data[R].length; ++C) {
      if (range.s.r > R) range.s.r = R;
      if (range.s.c > C) range.s.c = C;
      if (range.e.r < R) range.e.r = R;
      if (range.e.c < C) range.e.c = C;
      let cell = {
        v: data[R][C]
      };
      if (cell.v == null) continue;
      const cell_ref = XLSX.utils.encode_cell({
        c: C,
        r: R
      });
      if (typeof cell.v === "number") cell.t = "n";
      else if (typeof cell.v === "boolean") cell.t = "b";
      else if (cell.v instanceof Date) {
        cell.t = "n";
        cell.z = XLSX.SSF._table[14];
        cell.v = datenum(cell.v);
      } else cell.t = "s";
      ws[cell_ref] = cell;
    }
  }
  if (range.s.c < 10000000) ws["!ref"] = XLSX.utils.encode_range(range);
  return ws;
}

function s2ab(s) {
  let buf = new ArrayBuffer(s.length);
  let view = new Uint8Array(buf);
  for (let i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xff;
  return buf;
}

function Workbook() {
  if (!(this instanceof Workbook)) return new Workbook();
  this.SheetNames = [];
  this.Sheets = {};
}

/**
 * @description 导出表格数据
 * @param {Array} header 表头
 * @param {Array} data 数据
 * @param {String} filename 文件名
 * @param {merges} header 表头
 * @param {autoWidth} header 是否自适应表格内容宽度
 * @param {bookType} header excel文件后缀名
 */
export function exportJson2Excel({
  header = [],
  data = [],
  filename = "excel",
  merges = [],
  autoWidth = true,
  bookType = "xlsx"
} = {}) {
  let dataKeys = [];
  // 处理xlsx头部
  header = header.map(item => {
    dataKeys.push(item.key);
    return item.value;
  });
  // 处理data数据
  data = data.map(item => {
    const dataOne = dataKeys.map(key => item[key]);
    return [...dataOne];
  });
  header.length > 0 && data.unshift(header);
  let ws = sheet_from_array_of_arrays(data);
  if (merges.length > 0) {
    if (!ws["!merges"]) ws["!merges"] = [];
    merges.forEach(item => {
      ws["!merges"].push(XLSX.utils.decode_range(item));
    });
  }
  if (autoWidth) {
    // 设置worksheet每列的最大宽度
    const colWidth = data.map(row =>
      row.map(val => {
        // 先判断是否为null、undefined
        if (val == null) {
          return {
            wch: 10
          };
        } else if (val.toString().charCodeAt(0) > 255) {
          // 判断是否为中文
          return {
            wch: val.toString().length * 2
          };
        } else {
          return {
            wch: val.toString().length
          };
        }
      })
    );
    // 以第一行为初始值
    let result = colWidth[0];
    for (let i = 1; i < colWidth.length; i++) {
      for (let j = 0; j < colWidth[i].length; j++) {
        if (result[j]["wch"] < colWidth[i][j]["wch"]) {
          result[j]["wch"] = colWidth[i][j]["wch"];
        }
      }
    }
    ws["!cols"] = result;
  }
  const ws_name = "SheetJS";
  const wb = new Workbook();
  // 将工作表添加到工作簿
  wb.SheetNames.push(ws_name);
  wb.Sheets[ws_name] = ws;
  const wbout = XLSX.write(wb, {
    bookType: bookType,
    bookSST: false,
    type: "binary"
  });
  saveAs(
    new Blob([s2ab(wbout)], {
      type: "application/octet-stream"
    }),
    `${filename}.${bookType}`
  );
}

四、方法使用

<template>
  <div class="hello">
    <el-button type="primary" @click="handleExport">导出为Excel</el-button>
    <el-table :data="tableData" border>
      <el-table-column
        v-for="item in header"
        :key="item.key"
        :label="item.value"
        :prop="item.key"
      >
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import { exportJson2Excel } from "../utils/exportExcel.js";

export default {
  data() {
    return {
      message: "",
      header: [
        {
          key: "id",
          value: "ID"
        },
        {
          key: "title",
          value: "名称"
        },
        {
          key: "tag",
          value: "标签"
        },
        {
          key: "typeText",
          value: "方式"
        },
        {
          key: "cycle",
          value: "周期"
        },
        {
          key: "status",
          value: "状态"
        }
      ],
      tableData: [
        {
          id: 44,
          title: "test111122222",
          tag: "",
          typeText: "定时任务",
          cycle: "每天 9:00",
          status: "草稿"
        },
        {
          id: 45,
          title:
            "名称很长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长",
          tag: "hhh",
          typeText: "定时任务",
          cycle: "每天 12:00",
          status: "草稿"
        },
        {
          id: 45,
          title: "测试测试测试",
          tag: "hhh",
          typeText: "定时任务",
          cycle: "每天 00:00",
          status: "草稿"
        },
        {
          id: 47,
          title: "嗯嗯嗯",
          tag: "hhh",
          typeText: "定时任务",
          cycle: "每天 10:00",
          status: "草稿"
        },
        {
          id: 48,
          title: "test",
          tag: "null",
          typeText: "循环任务",
          cycle: "每天 19:00",
          status: "正式"
        }
      ]
    };
  },
  methods: {
    handleExport() {
      console.log("export");
      exportJson2Excel({
        data: this.tableData,
        header: this.header
      });
    }
};
</script>

页面页面展示,及导出结果:
在这里插入图片描述
在这里插入图片描述

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
要在Vue使用xlsx导出Excel文件,需要进行以下步骤: 1. 首先,在使用的页面中导入xlsxxlsx-style库。可以使用以下代码导入: ``` import XLSX from 'xlsx'; import XLSX2 from 'xlsx-style'; ``` 引用 2. 找到`./node_modules/xlsx-style/dist/cpexcel.js`文件,并手动修改其中的代码。将`var cpt = require('./cpt' 'able');`替换为`var cpt = cptable;`。这样做是为了解决Vue xlsx导出表格时间不全的问题。引用 3. 进行基本设置,并调用相应的函数来导出Excel文件。可以使用以下代码作为基础设置: ``` var data = this.addRangeBorder(wb['!merges'], wb); // 合并项添加边框 var filedata = this.sheet2blob(data); // 将一个sheet转成最终的excel文件的blob对象 this.openDownloadDialog(filedata, '报表名字.xlsx'); // 下载报表 ``` 引用 通过以上步骤,你就可以在Vue使用xlsx库来导出Excel文件了。记得根据自己的需求进行相应的调整和修改。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [vue框架使用xlsx导出excel表格](https://blog.csdn.net/qq_46372045/article/details/126779345)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

英子的搬砖日志

您的鼓励是我创作的动力~

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

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

打赏作者

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

抵扣说明:

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

余额充值