javascript技巧

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript技巧 > JS导出Excel通用方法

JS前端轻松导出Excel的通用方法详解

作者:记忆深处的声音

这篇文章主要介绍关于导出Excel通用方法的实用前端技巧,希望能够帮助大家更好地处理数据导出需求,接下来,我将为大家详细介绍这个方法和代码实现,需要的朋友可以参考下

背景

在项目开发中,我们经常遇到需要将数据导出为Excel文件的情况。然而,这个过程可能相对复杂和繁琐,特别是对于大量数据和复杂表格结构的情况。因此,我们需要一个通用方法,能够在各种场景下灵活使用,实现简单高效的数据导出操作

安装依赖:

npm install file-saver --save
npm install script-loader --save-dev
npm install xlsx --save

如果项目用的不是 npm 用 yarn 或 pnpm 一样的操作

在src下创建目录 vendor

目录下创建两个文件

Blob.js

/* eslint-disable */
(function (view) {
    "use strict";
    view.URL = view.URL || view.webkitURL;
    if (view.Blob && view.URL) {
        try {
            new Blob;
            return;
        } catch (e) { }
    }
    // Internally we use a BlobBuilder implementation to base Blob off of
    // in order to support older browsers that only have BlobBuilder
    var BlobBuilder = view.BlobBuilder || view.WebKitBlobBuilder || view.MozBlobBuilder || (function (view) {
        var
            get_class = function (object) {
                return Object.prototype.toString.call(object).match(/^[object\s(.*)]$/)[1];
            }
            , FakeBlobBuilder = function BlobBuilder() {
                this.data = [];
            }
            , FakeBlob = function Blob(data, type, encoding) {
                this.data = data;
                this.size = data.length;
                this.type = type;
                this.encoding = encoding;
            }
            , FBB_proto = FakeBlobBuilder.prototype
            , FB_proto = FakeBlob.prototype
            , FileReaderSync = view.FileReaderSync
            , FileException = function (type) {
                this.code = this[this.name = type];
            }
            , file_ex_codes = (
                "NOT_FOUND_ERR SECURITY_ERR ABORT_ERR NOT_READABLE_ERR ENCODING_ERR "
                + "NO_MODIFICATION_ALLOWED_ERR INVALID_STATE_ERR SYNTAX_ERR"
            ).split(" ")
            , file_ex_code = file_ex_codes.length
            , real_URL = view.URL || view.webkitURL || view
            , real_create_object_URL = real_URL.createObjectURL
            , real_revoke_object_URL = real_URL.revokeObjectURL
            , URL = real_URL
            , btoa = view.btoa
            , atob = view.atob
            , ArrayBuffer = view.ArrayBuffer
            , Uint8Array = view.Uint8Array
            ;
        FakeBlob.fake = FB_proto.fake = true;
        while (file_ex_code--) {
            FileException.prototype[file_ex_codes[file_ex_code]] = file_ex_code + 1;
        }
        if (!real_URL.createObjectURL) {
            URL = view.URL = {};
        }
        URL.createObjectURL = function (blob) {
            var
                type = blob.type
                , data_URI_header
                ;
            if (type === null) {
                type = "application/octet-stream";
            }
            if (blob instanceof FakeBlob) {
                data_URI_header = "data:" + type;
                if (blob.encoding === "base64") {
                    return data_URI_header + ";base64," + blob.data;
                } else if (blob.encoding === "URI") {
                    return data_URI_header + "," + decodeURIComponent(blob.data);
                } if (btoa) {
                    return data_URI_header + ";base64," + btoa(blob.data);
                } else {
                    return data_URI_header + "," + encodeURIComponent(blob.data);
                }
            } else if (real_create_object_URL) {
                return real_create_object_URL.call(real_URL, blob);
            }
        };
        URL.revokeObjectURL = function (object_URL) {
            if (object_URL.substring(0, 5) !== "data:" && real_revoke_object_URL) {
                real_revoke_object_URL.call(real_URL, object_URL);
            }
        };
        FBB_proto.append = function (data/*, endings*/) {
            var bb = this.data;
            // decode data to a binary string
            if (Uint8Array && (data instanceof ArrayBuffer || data instanceof Uint8Array)) {
                var
                    str = ""
                    , buf = new Uint8Array(data)
                    , i = 0
                    , buf_len = buf.length
                    ;
                for (; i < buf_len; i++) {
                    str += String.fromCharCode(buf[i]);
                }
                bb.push(str);
            } else if (get_class(data) === "Blob" || get_class(data) === "File") {
                if (FileReaderSync) {
                    var fr = new FileReaderSync;
                    bb.push(fr.readAsBinaryString(data));
                } else {
                    // async FileReader won't work as BlobBuilder is sync
                    throw new FileException("NOT_READABLE_ERR");
                }
            } else if (data instanceof FakeBlob) {
                if (data.encoding === "base64" && atob) {
                    bb.push(atob(data.data));
                } else if (data.encoding === "URI") {
                    bb.push(decodeURIComponent(data.data));
                } else if (data.encoding === "raw") {
                    bb.push(data.data);
                }
            } else {
                if (typeof data !== "string") {
                    data += ""; // convert unsupported types to strings
                }
                // decode UTF-16 to binary string
                bb.push(unescape(encodeURIComponent(data)));
            }
        };
        FBB_proto.getBlob = function (type) {
            if (!arguments.length) {
                type = null;
            }
            return new FakeBlob(this.data.join(""), type, "raw");
        };
        FBB_proto.toString = function () {
            return "[object BlobBuilder]";
        };
        FB_proto.slice = function (start, end, type) {
            var args = arguments.length;
            if (args < 3) {
                type = null;
            }
            return new FakeBlob(
                this.data.slice(start, args > 1 ? end : this.data.length)
                , type
                , this.encoding
            );
        };
        FB_proto.toString = function () {
            return "[object Blob]";
        };
        FB_proto.close = function () {
            this.size = this.data.length = 0;
        };
        return FakeBlobBuilder;
    }(view));
    view.Blob = function Blob(blobParts, options) {
        var type = options ? (options.type || "") : "";
        var builder = new BlobBuilder();
        if (blobParts) {
            for (var i = 0, len = blobParts.length; i < len; i++) {
                builder.append(blobParts[i]);
            }
        }
        return builder.getBlob(type);
    };
}(typeof self !== "undefined" && self || typeof window !== "undefined" && window || this.content || this));

Export2Excel.js

/* eslint-disable */
import {saveAs} from 'file-saver'
import * as XLSX from 'xlsx'
import XLSXS from "xlsx-style"
require('script-loader!file-saver');
require('./Blob');//这里是你的Blob.js的地址
require('script-loader!xlsx/dist/xlsx.core.min');
/**
 *
 * @param {*} table
 * @returns
 * 将HTML表格转换为二维数组
 * 函数支持处理表格中的单元格合并、行列跨度以及特定数据类型转换
 */
function generateArray(table) {
  let out = [];
  let rows = table.querySelectorAll('tr');
  let ranges = [];
  for (let R = 0; R < rows.length; ++R) {
    let outRow = [];
    let row = rows[R];
    let columns = row.querySelectorAll('td');
    for (let C = 0; C < columns.length; ++C) {
      let cell = columns[C];
      let colspan = cell.getAttribute('colspan');
      let rowspan = cell.getAttribute('rowspan');
      let cellValue = cell.innerText;
      if (cellValue !== "" && cellValue == +cellValue) cellValue = +cellValue;
      //Skip ranges
      ranges.forEach(function (range) {
        if (R >= range.s.r && R <= range.e.r && outRow.length >= range.s.c && outRow.length <= range.e
          .c) {
          for (let i = 0; i <= range.e.c - range.s.c; ++i) outRow.push(null);
        }
      });
      //Handle Row Span
      if (rowspan || colspan) {
        rowspan = rowspan || 1;
        colspan = colspan || 1;
        ranges.push({
          s: {
            r: R,
            c: outRow.length
          },
          e: {
            r: R + rowspan - 1,
            c: outRow.length + colspan - 1
          }
        });
      }
      ;
      //Handle Value
      outRow.push(cellValue !== "" ? cellValue : null);
      //Handle Colspan
      if (colspan)
        for (let k = 0; k < colspan - 1; ++k) outRow.push(null);
    }
    out.push(outRow);
  }
  return [out, ranges];
};
function datenum(v, date1904) {
  if (date1904) v += 1462;
  let epoch = Date.parse(v);
  return (epoch - new Date(Date.UTC(1899, 11, 30))) / (24 * 60 * 60 * 1000);
}
/**
 *
 * @param {*} data
 * @param {*} opts
 * @returns
 * 用于将二维数组转换为Excel工作表对象的JavaScript函数
 * 使用了XLSX.js库提供的工具方法来编码单元格引用和工作表范围,可生成可供Excel处理的工作表数据
 * 支持将一些数据类型转换为Excel支持的数据类型,例如将日期对象转换为数字类型,并设置相应的格式。
 */
function sheet_from_array_of_arrays(data, opts) {
  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;
      let 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 Workbook() {
  if (!(this instanceof Workbook)) return new Workbook();
  this.SheetNames = [];
  this.Sheets = {};
}
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;
}
export function export_table_to_excel(id) {
  let theTable = document.getElementById(id);
  let oo = generateArray(theTable);
  let ranges = oo[1];
  /* original data */
  let data = oo[0];
  let ws_name = "SheetJS";
  let wb = new Workbook(),
    ws = sheet_from_array_of_arrays(data);
  /* add ranges to worksheet */
  // ws['!cols'] = ['apple', 'banan'];
  ws['!merges'] = ranges;
  /* add worksheet to workbook */
  wb.SheetNames.push(ws_name);
  wb.Sheets[ws_name] = ws;
  let wbout = XLSX.write(wb, {
    bookType: 'xlsx',
    bookSST: false,
    type: 'binary'
  });
  saveAs(new Blob([s2ab(wbout)], {
    type: "application/octet-stream"
  }), "test.xlsx")
}
export function export_json_to_excelhb({
                                         multiHeader = [], //  第一行表头
                                         multiHeader2 = [], // 第二行表头
                                         header = [], // 第三行表头
                                         data,//传递的数据
                                         filename, //文件名
                                         merges = [], // 合并
                                         autoWidth = true,//用于设置列宽的
                                         bookType = 'xlsx'
                                       } = {}) {
  /* original data */
  filename = filename || '列表';
  data = [...data]
  for (let i = header.length - 1; i > -1; i--) {
    data.unshift(header[i])
  }
  for (let i = multiHeader2.length - 1; i > -1; i--) {
    data.unshift(multiHeader2[i])
  }
  for (let i = multiHeader.length - 1; i > -1; i--) {
    data.unshift(multiHeader[i])
  }
  let ws_name = "SheetJS";
  let wb = new Workbook(),
    ws = sheet_from_array_of_arrays(data);
  // 设置单元格公共样式
  let borderAll = { //单元格外侧框线
    top: {
      style: 'thin',
    },
    bottom: {
      style: 'thin',
    },
    left: {
      style: 'thin',
    },
    right: {
      style: 'thin',
    }
  };
  for (let key in ws) {
    // 单元格公共样式设置
    if (ws[key] instanceof Object) {
      ws[key].s = {
        border: borderAll,
        alignment: {
          horizontal: 'center', //水平居中对齐
          vertical: 'center',//垂直居中
          wrapText: 1,//自动换行
        },
        // fill: { //背景色
        //     fgColor: { rgb: 'dbf3f2' }
        // },
        font: {
          sz: 10,//单元格中字体的样式与颜色设置
          color: {
            rgb: '000000'
          }
        },
        bold: true,
        numFmt: 0
      }
    }
    //给特定格子(带'1'的,即首行 标题)添加样式,下面同理
    // if (key.replace(/[^0-9]/ig, '') === '1') {
    //     ws[key].s = {
    //         ...ws[key].s,
    //         fill: { //背景色
    //             fgColor: { rgb: 'd4e6fd' }
    //         },
    //         font: {//覆盖字体
    //             name: '等线',
    //             sz: 10,
    //             // bold: true
    //         },
    //     }
    // }
    if (key === 'A1') {
      ws[key].s = {
        ...ws[key].s,
        fill: { //背景色
          fgColor: {rgb: 'd4e6fd'}
        },
      }
    }
    // if (key === 'B2' || key === 'C2' || key === 'D2' || key === 'E2' || key === 'F2' || key === 'G2') {
    //     ws[key].s = {
    //         ...ws[key].s,
    //         fill: { //背景色
    //             fgColor: { rgb: 'fbedd7' }
    //         }
    //     }
    // }
  }
  if (merges.length > 0) {
    if (!ws['!merges']) ws['!merges'] = [];
    merges.forEach(item => {
      ws['!merges'].push(XLSX.utils.decode_range(
        XLSX.utils.encode_cell(item.s) + ':' + XLSX.utils.encode_cell(item.e)
      ));
      // 设置单元格的样式
      ws[XLSX.utils.encode_cell(item.s)].s = item.style;
    });
  }
  // ws['I2'] = ws['H2'] = ws['G2'] = ws['F2'] = ws['E2'] = ws['D2'] = ws['C2'] = ws['B2'] = ws['A2']//用于第二行的单元格的样式设置(如果是合并的第一行,就是1)
  // if (merges.length > 0) {
  //     if (!ws['!merges']) ws['!merges'] = [];
  //     merges.forEach(item => {
  //         console.log(item);
  //         ws['!merges'].push(XLSX.utils.decode_range(item))
  //     })
  // }
  if (autoWidth) {
    let colWidths = [];
    // 计算每一列的所有单元格宽度
    // 先遍历行
    data.forEach((row) => {
      // 列序号
      let index = 0
      // 遍历列
      for (const key in row) {
        if (colWidths[index] == null) colWidths[index] = []
        switch (typeof row[key]) {
          case 'string':
          case 'number':
          case 'boolean':
            colWidths[index].push(getCellWidth(row[key]))
            break
          case 'object':
          case 'function':
            colWidths[index].push(0)
            break
        }
        index++
      }
    })
    ws['!cols'] = [];
    // 第三行表头的设置
    colWidths.forEach((widths, index) => {
      // 计算列头的宽度
      // widths.push(getCellWidth(header[index]))
      // 设置最大值为列宽
      ws['!cols'].push({
        wch: Math.max(...widths)
      })
    })
  }
  /* add worksheet to workbook */
  wb.SheetNames.push(ws_name);
  wb.Sheets[ws_name] = ws;
  let wbout = XLSXS.write(wb, {
    bookType: bookType,
    bookSST: false,
    type: 'binary'
  });
  saveAs(new Blob([s2ab(wbout)], {
    type: "application/octet-stream"
  }), `${filename}.${bookType}`);
}
export function getCellWidth(value) {
  if (value == null) {
    return 10
  } else if (value.toString().charCodeAt(0) > 255) {
    // 判断是否包含中文
    let length = value.toString().length * 2
    if (length > 60) {
      length = length - 40
      //这里的宽度可以自己设定,在前面设置wrapText: 1可以在单元格内换行
    }
    return length
  } else {
    return value.toString().length * 1.2
  }
}
import {saveAs} from 'file-saver'
import * as XLSX from 'xlsx'
import XLSXS from "xlsx-style"
`file-saver`库中导入`saveAs`函数,用于保存文件。
`xlsx`库中导入所有的功能,并将其作为`XLSX`对象进行引用。
`xlsx-style`库导入是支持样式的,并将其命名为`XLSXS`。
require('script-loader!file-saver'); 
require('./Blob');//这里是你的Blob.js的地址 
require('script-loader!xlsx/dist/xlsx.core.min');
这部分代码使用`require`和`script-loader`来加载和引入所需的脚本文件。
其中,通过`script-loader!file-saver`来加载`file-saver`库所需要的脚本,
`require('./Blob')`用于加载自定义的`Blob.js`文件,
`script-loader!xlsx/dist/xlsx.core.min`用于加载`xlsx`库的核心脚本。

上述代码片段中的具体路径和文件名可能因你的项目结构而有所不同,你需要根据实际情况进行调整。

通过以上步骤,你可以在项目中使用saveAs()函数将文件保存到本地,以及使用XLSXXLSXS对象进行 Excel 文件的处理和操作。

代码实现

Blob.js 和Export2Excel.js 两个文件网上有很多,根据个人项目有细微不同,基本大同小异, 但是在项目有非常多的数据图表以及各种不同类型的表格。不做封装通用方法,代码重复量便会增多并且不易维护

因此,我基于Export2Excel中做了一个通用方法,代码如下:

创建 vendor/exportExcel.js 文件

// 导出Excel通用方法
async function exportExcel(multiHeader, multiHeader2, filterVal, tableData, tabulationTitle, indexNumber) {
  // 导出标题
  const EXPORT_FILENAME = tabulationTitle;
  // 单元格样式1 dbf3f2
  const style1 = {
    fill: {patternType: 'solid', fgColor: {rgb: 'dbf3f2'}},
    border: {top: {style: 'thin'}, left: {style: 'thin'}, bottom: {style: 'thin'}, right: {style: 'thin'}},
    alignment: {horizontal: 'center', vertical: 'center', wrapText: 1}
  };
  // 单元格样式2 fbedd7
  const style2 = {
    fill: {patternType: 'solid', fgColor: {rgb: 'fbedd7'}},
    border: {top: {style: 'thin'}, left: {style: 'thin'}, bottom: {style: 'thin'}, right: {style: 'thin'}},
    alignment: {horizontal: 'center', vertical: 'center', wrapText: 1}
  };
  // 进行所有表头的单元格合并
  let headerList = [];
  let titleList = [];
  let styleNumber = 1; // 初始为1 1级表头样式判断
  let headerStyle = style2;
  let rowIndex = 1;
  let colIndex = 1;
  let isOdd = true;
  let count = 0;
  const indexNumber2 = indexNumber + 1
  // 一级表头合并与颜色赋值
  if (multiHeader[0] && multiHeader[0].length > 0) {
    multiHeader[0].forEach((group, index) => {
      if (rowIndex < multiHeader[0].length) {
        headerList.push({s: {r: 0, c: rowIndex}, e: {r: 0, c: rowIndex + indexNumber}, style: headerStyle});
        rowIndex += indexNumber2;
      }
      // 修改样式值
      if (styleNumber === 1) {
        styleNumber = 2 // 修改样式值
        headerStyle = style1
      } else {
        styleNumber = 1 // 修改样式值
        headerStyle = style2
      }
    });
  }
  if (multiHeader2[0] && multiHeader2[0].length > 0) {
    multiHeader2[0].forEach((group, index) => {
      if (colIndex < multiHeader2[0].length) {
        titleList.push({s: {r: 1, c: colIndex}, e: {r: 1, c: colIndex}, style: isOdd ? style2 : style1});
        colIndex += 1;
        count++;
      }
      if (count % indexNumber2 === 0) {
        isOdd = !isOdd;
      }
    });
  }
  // 进行所有表头的单元格合并
  const merges = [
    // 将A1和A2合并,并设置背景色1
    {
      s: {r: 0, c: 0},
      e: {r: 1, c: 0},
      style: {
        fill: {patternType: 'solid', fgColor: {rgb: 'd4e6fd'}},
        border: {top: {style: 'thin'}, left: {style: 'thin'}, bottom: {style: 'thin'}, right: {style: 'thin'}},
        alignment: {horizontal: 'center', vertical: 'center', wrapText: 1}
      }
    },
    ...headerList,
    ...titleList // 二级表头
  ];
  const data = tableData.map((v) => filterVal.map((j) => v[j]));
  await import('/src/vendor/Export2Excel.js').then((excel) => {
    excel.export_json_to_excelhb({
      multiHeader, // 这里是第一行的表头
      multiHeader2, // 这里是第二行的表头
      data,
      filename: EXPORT_FILENAME,
      merges
    });
  });
}
export default {exportExcel}

上面给出的代码是一个导出Excel通用方法的示例。让我们逐步解析其中的关键逻辑:

导出示例

main.js引入全局

import Excel from './vendor/exportExcel'
Vue.prototype.$Excel = Excel;
// 调用导出Excel通用方法
async exportExcelDemo() {
  let multiHeader = []; // 第一行的表头
  let multiHeader2 = [] // 第二行的表头
  let filterVal = [] // 对应字段
  multiHeader = [[this.areaNameText, '游戏厅', '', '', '游戏厅', '', '', '网咖', '', '',]]
  multiHeader2 = [['', this.current, this.text, '同比去年', this.current, this.text, '同比去年', this.current, this.text, '同比去年',]];
  filterVal = ['areaName',
                    'sumValue03', 'momPerCent', 'yoyPerCent',
                    'sumValue032', 'momPerCent2', 'yoyPerCent2',
                    'sumValue033', 'momPerCent3', 'yoyPerCent3',
                ];
  const tabulationTitle = '导出表格'; // 导出标题
  const indexNumber = this.activeDate === 'day' ? 6 : 7 // 根据业务需求进行调整 需要的字段数据也不同
  await this.$Excel.exportExcel(multiHeader, multiHeader2, filterVal, tableData, tabulationTitle,indexNumber);
}
// 调用示例
this.exportExcelDemo();

应用场景

这个通用的导出Excel方法适用于多种前端开发场景,比如:

总结

通过这个通用的导出Excel方法,我们能够轻松地处理各种数据导出需求,并且能够适应不同的表格结构和数据量。只需简单配置参数,就能生成美观、便于阅读和处理的Excel文件。

希望这篇文章能够对大家在前端开发中的数据导出需求有所帮助。

以上就是JS前端轻松导出Excel的通用方法详解的详细内容,更多关于JS导出Excel通用方法的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
阅读全文