JS前端转Excel,带样式

exportTable(selector, fileName) {
    let tableDom = document.querySelector(selector);
    let wb = XLSX.utils.table_to_book(tableDom);

    for (const key in wb.Sheets.Sheet1) {
      if (Object.prototype.toString.call(wb.Sheets.Sheet1[key]) === '[object Object]') {
        //给每个格子修改样式
        wb.Sheets.Sheet1[key].s = {
          //字体水平居中、垂直居中、自动换行、缩进
          alignment: {
            horizontal: 'center', //水平居中
            vertical: 'center',
            wrapText: 1,
            indent: 0
          },
          //大小
          font: {
            sz: 15,
          },
          border: {
            //单元格外侧框线
            top: {
              style: "thin",
            },
            bottom: {
              style: "thin",
            },
            left: {
              style: "thin",
            },
            right: {
              style: "thin",
            },
          }
        }
      }
      wb.Sheets.Sheet1['!cols'].push({wpx: 150});
    }

    let wbout = XLSX.write(wb, {
      bookType: "xlsx",
      bookSST: true,
      type: "array",
      cellStyles: true
    });
    try {
      saveAs(
        new Blob([wbout], {type: "application/octet-stream"}),
        (fileName || "数据导出-" + parseTime(new Date(), "{y}{m}{d}_{h}{i}{s}")) +
        ".xlsx"
      );
    } catch (e) {
    }
    return wbout;
  }

需要安装 xlsx-js-style 和 file-saver 插件,目前已经控制了字体的大小,单元格的大小,单元格的水平居中,比默认的好看多了。

你可能感兴趣的:(前端,javascript,excel)