88 lines
2.3 KiB
TypeScript
88 lines
2.3 KiB
TypeScript
import { JSON2SheetOpts, read, utils, write } from 'xlsx';
|
||
|
||
// 静态资源路径
|
||
const baseUrl = import.meta.env.VITE_HISTORY_BASE_URL;
|
||
export const xlsxUrl = `${
|
||
baseUrl.length === 1 && baseUrl.indexOf('/') === 0
|
||
? ''
|
||
: baseUrl.indexOf('/') === -1
|
||
? '/' + baseUrl
|
||
: baseUrl
|
||
}/alarmHelp`;
|
||
|
||
/**
|
||
* 读取本地文件
|
||
* @param id 表格ID
|
||
* @returns 数据数组
|
||
* @example
|
||
* readLoalXlsx('20001').then(res=>{
|
||
* console.log(res)
|
||
* });
|
||
*/
|
||
export async function readLoalXlsx(
|
||
lang: string,
|
||
id: string
|
||
): Promise<Record<string, any>[]> {
|
||
let result = await fetch(`${xlsxUrl}/${lang}/${id}.xlsx`);
|
||
let fileBuffer = await result.arrayBuffer();
|
||
// 判断是否xlsx文件
|
||
const data = new Uint8Array(fileBuffer);
|
||
const isXlsxFile =
|
||
data[0] === 0x50 &&
|
||
data[1] === 0x4b &&
|
||
data[2] === 0x03 &&
|
||
data[3] === 0x04;
|
||
if (!isXlsxFile) {
|
||
result = await fetch(`${xlsxUrl}/${lang}/all.xlsx`);
|
||
fileBuffer = await result.arrayBuffer();
|
||
}
|
||
return readSheet(fileBuffer, 0);
|
||
}
|
||
|
||
/**
|
||
* 读取表格数据 工作表
|
||
* @param fileBolb 文件对象
|
||
* @param index 文件保存路径
|
||
* @return 表格对象列表
|
||
*/
|
||
export async function readSheet(
|
||
fileBolb: Blob | ArrayBuffer,
|
||
index: number = 0
|
||
): Promise<Record<string, string>[]> {
|
||
const workBook = read(fileBolb);
|
||
let workSheet = workBook.Sheets[workBook.SheetNames[index]];
|
||
return utils.sheet_to_json<Record<string, string>>(workSheet);
|
||
}
|
||
|
||
/**
|
||
* 写入表格数据,一般用于导出
|
||
* @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,
|
||
opts?: JSON2SheetOpts
|
||
) {
|
||
if (data.length === 0) {
|
||
return new Blob([], { type: 'application/octet-stream' });
|
||
}
|
||
|
||
const workSheet = utils.json_to_sheet(data, opts);
|
||
|
||
// 设置列宽度,单位厘米
|
||
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' });
|
||
}
|