导出的使用

[复制链接]
发表于 2025-3-23 02:43:51 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
一.导出的具体使用步骤

1.在web开发中,导出是很常见的一个功能,当我举行个人项目练习的时候,导出的时候无法控制列宽以及居中样式,后续发现导出插件无法举行修改,整个插件较为简便易懂的同时,对于EX的控制较为简陋,许多东西并不能设置,根据我的搜刮,更改为ExcelJS插件来控制样式以及列宽,停止于现在
引用方式

  1.   <script src="https://cdn.jsdelivr.net/npm/
  2. [email protected]/dist/exceljs.min.js"></script>
复制代码
来得到对应的方法进利用用
2.在实现导出功能之前,我们需要对一些配置举行初始化。下面是配置对象的内容,其中包罗了导出字段、表头映射、状态映射和样式配置等:
  1. // 导出配置
  2. const exportConfig = {
  3.   // 选择导出的字段路径
  4.   selectedHeaders: [
  5.     "id",
  6.     "user.nickname",
  7.     "card",
  8.     "tel",
  9.     "depart.name",
  10.     "doctor_name",
  11.     "money",
  12.     "status",
  13.     "visit_status",
  14.     "order_code",
  15.     "create_time",
  16.     "yes_time",
  17.   ],
  18.   // 表头映射关系
  19.   customHeaders: {
  20.     id: "订单ID",
  21.     "user.nickname": "就诊人",
  22.     card: "就诊卡号",
  23.     tel: "手机号",
  24.     "depart.name": "挂号科室",
  25.     doctor_name: "医生姓名",
  26.     money: "支付金额",
  27.     status: "缴费状态",
  28.     visit_status: "就诊状态",
  29.     order_code: "订单号",
  30.     create_time: "创建时间",
  31.     yes_time: "最后缴费时间",
  32.   },
  33.   // 状态映射配置
  34.   statusMappings: {
  35.     status: {
  36.       2: "欠费",
  37.       1: "缴费完成",
  38.       null: "未知",
  39.       undefined: "未知",
  40.     },
  41.     visit_status: {
  42.       2: "就诊中",
  43.       1: "就诊完成",
  44.       null: "未知",
  45.       undefined: "未知",
  46.     },
  47.   },
  48.   // 样式配置
  49.   columnWidth: 18,
  50.   styles: {
  51.     header: {
  52.       fill: {
  53.         type: "pattern",
  54.         pattern: "solid",
  55.         fgColor: { argb: "FFD3D3D3" },
  56.       },
  57.       font: {
  58.         bold: true,
  59.         name: "微软雅黑",
  60.         size: 12,
  61.       },
  62.       alignment: {
  63.         vertical: "middle",
  64.         horizontal: "center",
  65.       },
  66.     },
  67.     body: {
  68.       font: {
  69.         name: "微软雅黑",
  70.         size: 11,
  71.       },
  72.       alignment: {
  73.         vertical: "middle",
  74.         horizontal: "center",
  75.       },
  76.     },
  77.   },
  78. };
复制代码


  • selectedHeaders: 这是一个包含了需要导出的字段路径的数组。每个路径指向数据对象中的一个字段,可以是嵌套的字段(比方:"user.nickname")。
  • customHeaders: 这是字段的映射,用于将字段路径映射到Excel表格中的实际表头名称。
  • statusMappings: 配置字段状态的映射,如"缴费状态"和"就诊状态"的数值映射为具体的状态形貌。
  • styles: 设置Excel表格的样式,如字体、对齐方式、填充色等。
二.工具函数

为了从数据源中提取嵌套值,我们编写了以下工具函数:
getNestedValue

该函数用于从对象中根据路径提取嵌套的值:
  1. function getNestedValue(obj, path) {
  2.   return path.split(".").reduce((acc, key) => {
  3.     if (acc === null || acc === undefined) return undefined;
  4.     return acc[key];
  5.   }, obj);
  6. }
复制代码
formatDate

该函数将时间戳转换为易读的日期格式:
  1. function formatDate(timestamp) {
  2.   if (!timestamp) return "未知时间";
  3.   const date = new Date(timestamp);
  4.   return `${date.getFullYear()}-${(date.getMonth() + 1)
  5.     .toString()
  6.     .padStart(2, "0")}-${date.getDate().toString().padStart(2, "0")} ${date
  7.     .getHours()
  8.     .toString()
  9.     .padStart(2, "0")}:${date.getMinutes().toString().padStart(2, "0")}`;
  10. }
复制代码
三.数据处理与Excel生成

在数据导出的核心函数exportData中,我们首先对数据源举行有效性查抄和预处理。数据的每一项都会通过配置举行映射和处理,特别是数字格式、日期格式和状态映射。
  1. async function exportData(dataSource) {
  2.   try {
  3.     if (!dataSource || !Array.isArray(dataSource)) {
  4.       throw new Error("无效的数据源");
  5.     }
  6.     if (dataSource.length === 0) {
  7.       showAlerts(".ErrorModal", "5%", "警告:没有可导出的数据");
  8.       return;
  9.     }
  10.     const processedData = dataSource.map((item) => {
  11.       const rowData = {};
  12.       exportConfig.selectedHeaders.forEach((fieldPath) => {
  13.         const displayName = exportConfig.customHeaders[fieldPath];
  14.         let rawValue = getNestedValue(item, fieldPath);
  15.         // 状态映射处理
  16.         if (exportConfig.statusMappings[fieldPath]) {
  17.           rawValue =
  18.             exportConfig.statusMappings[fieldPath][rawValue] ?? "未知状态";
  19.         }
  20.         // 特殊字段处理
  21.         if (fieldPath === "money") {
  22.           const numericString = String(rawValue).replace(/[^0-9.]/g, "");
  23.           const numericValue = parseFloat(numericString);
  24.           if (!isNaN(numericValue) && isFinite(numericValue)) {
  25.             rawValue = numericValue;
  26.           } else {
  27.             rawValue = "金额异常";
  28.             showAlerts(".ErrorModal", "5%", "金额异常");
  29.           }
  30.         }
  31.         if (["create_time", "yes_time"].includes(fieldPath)) {
  32.           rawValue = formatDate(rawValue);
  33.         }
  34.         // 默认空值处理
  35.         if ([null, undefined, ""].includes(rawValue)) {
  36.           rawValue = fieldPath.includes("time") ? "时间未记录" : "未知";
  37.         }
  38.         rowData[displayName] = rawValue;
  39.       });
  40.       return rowData;
  41.     });
  42.     // 创建Excel工作簿
  43.     const workbook = new ExcelJS.Workbook();
  44.     const worksheet = workbook.addWorksheet("门诊缴费记录", {
  45.       properties: { tabColor: { argb: "FF00FF00" } },
  46.     });
  47.     // 添加表头
  48.     const headers = Object.values(exportConfig.customHeaders);
  49.     const headerRow = worksheet.addRow(headers);
  50.     headerRow.eachCell((cell) => {
  51.       cell.style = exportConfig.styles.header;
  52.     });
  53.     // 添加数据行
  54.     processedData.forEach((dataItem) => {
  55.       const rowValues = headers.map((header) => dataItem[header]);
  56.       const dataRow = worksheet.addRow(rowValues);
  57.       dataRow.eachCell((cell) => {
  58.         cell.style = exportConfig.styles.body;
  59.       });
  60.     });
  61.     // 设置列宽
  62.     worksheet.columns = headers.map(() => ({
  63.       width: 20,
  64.       style: { numFmt: "@" },
  65.     }));
  66.     // 生成文件
  67.     const buffer = await workbook.xlsx.writeBuffer();
  68.     const blob = new Blob([buffer], {
  69.       type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  70.     });
  71.     const downloadLink = document.createElement("a");
  72.     downloadLink.href = URL.createObjectURL(blob);
  73.     downloadLink.download = `门诊缴费记录_${new Date().toISOString().slice(0, 10)}_${hours}:${minutes}:${seconds}.xlsx`;
  74.     document.body.appendChild(downloadLink);
  75.     downloadLink.click();
  76.     // 清理资源
  77.     setTimeout(() => {
  78.       URL.revokeObjectURL(downloadLink.href);
  79.       downloadLink.remove();
  80.     }, 1000);
  81.   } catch (error) {
  82.     console.error("导出过程中发生错误:", error);
  83.     alert(`导出失败: ${error.message}`);
  84.   }
  85. }
复制代码
核心步骤


  • 数据预处理: 根据配置映射数据字段,并处理特殊字段(如金额、日期等)。
  • Excel生成: 使用ExcelJS创建工作簿,并设置表头和数据行的样式。
  • 导出功能: 生成Excel文件并通过Blob触发下载。
四.用户交互与事件处理

在页面交互中,我们提供了全选、反选和导出选中项/全部数据的功能。用户可以根据需求选择需要导出的数据,或选择导出全部数据。
事件处理代码

  1. $(document).ready(function () {
  2.   $(".select-all").on("change", function () {
  3.     $(".row-checkbox").prop("checked", this.checked);
  4.   });
  5.   $(".choice_export").on("click", async function () {
  6.     const selectedIndexes = $(".notice .checkbox_id input:checked")
  7.       .map(function () {
  8.         return $(this).attr("dataIndex");
  9.       })
  10.       .get();
  11.     if (selectedIndexes.length === 0) {
  12.       showAlerts(".ErrorModal", "5%", "请至少选择一条有效记录");
  13.       return;
  14.     }
  15.     try {
  16.       const selectedData = globalData.filter((item) =>
  17.         selectedIndexes.includes(item.id.toString())
  18.       );
  19.       await exportData(selectedData);
  20.       showAlerts(".correctModal", "5%", `成功导出 ${selectedData.length} 条数据`, "success");
  21.     } catch (error) {
  22.       showAlerts(".ErrorModal", "5%", `导出失败: ${error.message}`, "error");
  23.     }
  24.   });
  25.   $(".all_export").on("click", async function () {
  26.     if (!globalData || globalData.length === 0) {
  27.       showAlerts(".ErrorModal", "5%", "当前没有可导出的数据");
  28.       return;
  29.     }
  30.     try {
  31.       await exportData(globalData);
  32.       showAlerts(".correctModal", "5%", "成功导出全部数据");
  33.     } catch (error) {
  34.       showAlerts(".ErrorModal", "5%", `导出失败: ${error.message}`, "error");
  35.     }
  36.   });
  37. });
复制代码
总结

本文介绍了怎样使用ExcelJS库举行数据导出,涵盖了怎样处理数据映射、设置自定义表头、实现状态映射、格式化日期和金额、以及怎样生成和下载Excel文件。通过这些步骤,你可以轻松实现复杂的Excel导出功能,并根据差别的业务需求举行调解和扩展。
回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表