diff --git a/src/utils/index.js b/src/utils/index.js index 2eb7065..7c1eceb 100644 --- a/src/utils/index.js +++ b/src/utils/index.js @@ -563,3 +563,21 @@ export function isRegent(item, fieldCode = 'type') { ] return typeList.includes(type) } +/** + * 估算字符串在 Excel 中的显示宽度(简单规则:中文字符算2,英文字符算1) + * @param {string} str 要计算的字符串 + * @returns {number} 估算宽度 + */ +export function getStringWidth(str) { + if (!str) return 0 + let width = 0 + for (let char of str.toString()) { + // 中文字符范围(可根据需要扩展) + if (/[\u4e00-\u9fa5]/.test(char)) { + width += 2 + } else { + width += 1 + } + } + return width +} diff --git a/src/views/business/comps/template/mixins/templateMixin.js b/src/views/business/comps/template/mixins/templateMixin.js index 46b73ea..7ccff69 100644 --- a/src/views/business/comps/template/mixins/templateMixin.js +++ b/src/views/business/comps/template/mixins/templateMixin.js @@ -1,10 +1,11 @@ import moment from 'moment' import { getLatestSn, getLatestSnArr } from '@/api/template'; -import { isValueEmpty } from '@/utils/index'; +import { isValueEmpty, getStringWidth } from '@/utils/index'; import { isCommonUnit } from "@/utils/conTools"; import { sj_subpackage, sj_startConfiguration, sj_configurationCompleted } from '@/api/business/sj/sj'; import {convertConcentration} from "@/utils/conConverter";//浓度单位转换 import {volumeConverter} from "@/utils/volConverter";//体积单位转换 +import * as XLSX from 'xlsx' export default { dicts: [ 'business_pztj', @@ -602,54 +603,16 @@ export default { } }, // 导出excel模板 - exportExcel(rows, title) { + exportExcel(headerArray, title = '导出模板') { this.$modal.loading() - // 生成表头 - let tableHtml = ''; - tableHtml += ''; - rows.forEach(item => { - tableHtml += ''; - }); - tableHtml += '
' + item + '
'; // 正确闭合 - - // Worksheet 名称 - const worksheet = title ? title : '导入模板'; - - // 完整的 HTML 模板(包含编码声明和 Excel 兼容命名空间) - const exportTemplate = ` - - - - - - - ${tableHtml} - - `; - - // 使用 Blob 生成文件(指定 MIME 类型为 application/vnd.ms-excel) - const blob = new Blob([exportTemplate], { type: 'application/vnd.ms-excel;charset=utf-8' }); - const link = document.createElement('a'); - link.href = URL.createObjectURL(blob); - link.download = worksheet + '.xls'; - link.click(); - URL.revokeObjectURL(link.href); // 释放内存 + const ws = XLSX.utils.aoa_to_sheet([headerArray]); + const colWidths = headerArray.map(cell => getStringWidth(cell) + 2); + ws['!cols'] = colWidths.map(width => ({ wch: width })); + const wb = XLSX.utils.book_new(); + XLSX.utils.book_append_sheet(wb, ws, 'Sheet1'); + XLSX.writeFile(wb, `${title}.xlsx`); this.$modal.closeLoading() }, + } }