From 9316d950b14da779d59ea41356727c50e5f6db64 Mon Sep 17 00:00:00 2001 From: c37csq <1903498134@qq.com> Date: Thu, 29 Sep 2022 10:11:26 +0800 Subject: [PATCH] fix: excel export set width (#2206) --- src/components/Excel/src/Export2Excel.ts | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/src/components/Excel/src/Export2Excel.ts b/src/components/Excel/src/Export2Excel.ts index 952ac45f1..16a0ddae7 100644 --- a/src/components/Excel/src/Export2Excel.ts +++ b/src/components/Excel/src/Export2Excel.ts @@ -6,6 +6,28 @@ const { utils, writeFile } = xlsx; const DEF_FILE_NAME = 'excel-list.xlsx'; +/** + * @param data source data + * @param worksheet worksheet object + * @param min min width + */ +function setColumnWidth(data, worksheet, min = 3) { + const obj = {}; + worksheet['!cols'] = []; + data.forEach((item) => { + Object.keys(item).forEach((key) => { + const cur = item[key]; + const length = cur.length; + obj[key] = Math.max(min, length); + }); + }); + Object.keys(obj).forEach((key) => { + worksheet['!cols'].push({ + wch: obj[key], + }); + }); +} + export function jsonToSheetXlsx({ data, header, @@ -20,7 +42,7 @@ export function jsonToSheetXlsx({ } const worksheet = utils.json_to_sheet(arrData, json2sheetOpts); - + setColumnWidth(arrData, worksheet); /* add worksheet to workbook */ const workbook: WorkBook = { SheetNames: [filename],