diff --git a/src/utils/execl-utils.ts b/src/utils/execl-utils.ts index ab735e12..2358e4b1 100644 --- a/src/utils/execl-utils.ts +++ b/src/utils/execl-utils.ts @@ -1,10 +1,8 @@ -import { read, utils } from 'xlsx'; +import { read, utils, write } from 'xlsx'; -/** - * ×ÖÌåͼ±êÎļþ-¾²̬×ÊԴÎļþ·¾¶ - */ +// 静态资源路径 const baseUrl = import.meta.env.VITE_HISTORY_BASE_URL; -export const scriptUrl = `${ +export const xlsxUrl = `${ baseUrl.length === 1 && baseUrl.indexOf('/') === 0 ? '' : baseUrl.indexOf('/') === -1 @@ -12,19 +10,54 @@ export const scriptUrl = `${ : baseUrl }/alarmHelp`; - +/** + * 读取本地文件 + * @param id 表格ID + * @returns 数据数组 + * @example + * readLoalXlsx('20001').then(res=>{ + * console.log(res) + * }); + */ +export async function readLoalXlsx(id: string): Promise[]> { + const fileBolb = await (await fetch(`${xlsxUrl}/${id}.xlsx`)).arrayBuffer(); + return readSheet(fileBolb, 0); +} /** - * ¸ñʽʱ¼ä×ַû´® - * @param dateStr ʱ¼ä×ַû´® - * @param formatStr ʱ¼ä¸ñʽ ĬÈÏYYYY-MM-DD HH:mm:ss - * @returns Date¶ÔÏó + * 读取表格数据 工作表 + * @param fileBolb 文件对象 + * @param index 文件保存路径 + * @return 表格对象列表 */ -export async function parseStrToDate(): Promise[]> { +export async function readSheet( + fileBolb: Blob | ArrayBuffer, + index: number = 0 +): Promise[]> { + const workBook = read(fileBolb); + let workSheet = workBook.Sheets[workBook.SheetNames[index]]; + return utils.sheet_to_json>(workSheet); +} - const f = await (await fetch(scriptUrl+"/20001.xlsx")).arrayBuffer(); - const wb = read(f);1 - const data = utils.sheet_to_json< Record>(wb.Sheets[wb.SheetNames[0]]); - console.log(data); - return data; - } \ No newline at end of file +/** + * 写入表格数据,一般用于导出 + * @param filePath 文件路径 + * @param sheetName 工作表名称 + * @return xlsx文件流, 使用saveAs函数保存 + * @example + * writeSheet(res.data, from.logType).then(fileBlob => + * saveAs(fileBlob, `${from.logType}_${Date.now()}.xlsx`) + * ); + * + */ +export async function writeSheet(data: any[], sheetName: string) { + const workSheet = utils.json_to_sheet(data); + // 设置列宽度,单位厘米 + workSheet['!cols'] = Object.keys(data[0]).map(() => { + return { wch: 20 }; + }); + const workBook = utils.book_new(); + utils.book_append_sheet(workBook, workSheet, sheetName); + const excelBuffer = write(workBook, { type: 'array', bookType: 'xlsx' }); + return new Blob([excelBuffer], { type: 'application/octet-stream' }); +}