前端实现excel导出表格(纯前端实现)

1.先安装相应的插件

npm install [email protected]
npm install file-saver
npm install xlsx-style-medalsoft

2.封装好公共导出功能。我这里在utils文件夹下的tools.js

import FileSaver from "file-saver";
import XLSX from "xlsx";
import XLSXStyle from "xlsx-style-medalsoft";

const OMS = {};

// 导出Excel-单表格Excel  带样式
OMS.downLoadXlsx = ({
  dom = "el-table",
  name = "文件",
  ColumnWdth = [],
  rowName = null,
}) => {
  const table = document.getElementById(dom);
  //   因为element-ui的表格的fixed属性导致多出一个table,会下载重复内容,这里删除掉
  if (table.querySelector(".el-table__fixed")) {
    table.removeChild(table.querySelector(".el-table__fixed"));
  }
  if (table.querySelector(".el-table__fixed-right")) {
    table.removeChild(table.querySelector(".el-table__fixed-right"));
  }
  const et = XLSX.utils.table_to_book(table, { raw: true }); // 此处传入table的DOM节点,raw为true表示单元格为文本格式(未加工)
  const wbs = et.Sheets.Sheet1;

  // 删掉末尾空行
  Object.keys(wbs).forEach((item, index) => {
    if (!item.startsWith("!") && wbs[item].v === "") {
      delete wbs[item];
    }
    if (rowName) {
      if (item.includes(rowName)) {
        delete wbs[item];
      }
    }
  });
  console.log(wbs, "wbs");
  // debugger;
  // 设置表格列宽度
  if (ColumnWdth.length === 0) {
    for (let i = 0; i < 30; i++) {
      wbs["!cols"][i] = { wch: 12.5 };
    }
  } else {
    ColumnWdth.forEach((item, i) => {
      wbs["!cols"][i] = { wch: item };
    });
  }

  // 循环遍历每一个表格,设置样式
  for (const key in wbs) {
    if (!key.startsWith("!")) {
      wbs[key].s = {
        font: {
          sz: 11, // 字体大小
          bold: false, // 加粗
          name: "宋体", // 字体
          color: {
            rgb: "000000", // 十六进制,不带#
          },
        },
        alignment: {
          // 文字居中
          horizontal: "center",
          vertical: "center",
          wrapText: false, // 文本自动换行
        },
        border: {
          // 设置边框
          top: { style: "thin" },
          bottom: { style: "thin" },
          left: { style: "thin" },
          right: { style: "thin" },
        },
      };
    }
  }

  const arr = [
    "A",
    "B",
    "C",
    "D",
    "E",
    "F",
    "G",
    "H",
    "I",
    "J",
    "K",
    "L",
    "M",
    "N",
    "O",
    "P",
    "Q",
    "R",
    "S",
    "T",
    "U",
    "V",
    "W",
    "X",
    "Y",
    "Z",
  ];

  // 行列合并
  const range = wbs["!merges"];
  if (range) {
    range.forEach((item) => {
      const startColNumber = Number(item.s.r);
      const endColNumber = Number(item.e.r);
      const startRowNumber = Number(item.s.c);
      const endRowNumber = Number(item.e.c);
      const test = wbs[arr[startRowNumber] + (startColNumber + 1)];
      for (let col = startColNumber; col <= endColNumber; col++) {
        for (let row = startRowNumber; row <= endRowNumber; row++) {
          wbs[arr[row] + (col + 1)] = test;
        }
      }
    });
  }

  const etout = XLSXStyle.write(et, {
    bookType: "xlsx",
    type: "buffer",
  });
  // eslint-disable-next-line no-useless-catch
  try {
    FileSaver.saveAs(
      new Blob([etout], { type: "application/octet-stream" }),
      `${name}.xlsx`
    ); // 导出的文件名
  } catch (e) {
    throw e;
  }
};

export default OMS;

3.页面中使用

给表格绑定一个id,通过获取dom来导出

import OMS from "@/utils/tools";


     <el-table
          v-if="showTable"
          id="kuTable"
          max-height="525"
          v-loading="loading"
          :data="wmsStockList"
          @selection-change="handleSelectionChange"
        >
               </el-table>

// 导出
    handleExport() {
      // const that = this
      this.$confirm("是否确认导出入库列表?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          //   console.log(this.pmsSpuInfoList, "this.pmsSpuInfoList");
          this.exportLoading = true;
          OMS.downLoadXlsx({
            dom: "kuTable",
            name: "入库列表",
            ColumnWdth: [
              12, 12, 20, 30, 20, 20, 30, 20, 40, 12, 20, 12, 14, 15, 15,
            ], // 每一列的宽度,需要直接指定,接受数字
            rowName: "P", //可以设置哪行不要的
          });
          this.exportLoading = false;
          this.showTable = false;
          this.$nextTick(() => {
            // this.getList();
            this.showTable = true;
          });
        })
        .catch(function () {});
    },

4.效果图

猜你喜欢

转载自blog.csdn.net/liang04273/article/details/135423618