xlsx.ts
3.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
/**
* xlsx / csv 解码(适配器层,壳的一部分)。
*
* 这是把「用户上传的字节」变成「表头 + 行数组」的地方 —— 它不属于清洗算法(@hm/clean-core),
* 而是算法跑之前的 IO 预处理。算法包因此保持纯净、可被任意宿主复用;解码这层则由各自的壳负责。
*
* 与 app 的 ingestCore 同一套口径:
* - xlsx / xls / zip 走 SheetJS(`type: 'array'` 必须喂 Uint8Array);
* - csv 走自研严格 UTF-8 解码,失败退 GBK(Excel 另存的 CSV 常见),避免中文乱码把区/街道全判成「未识别」。
*/
import * as XLSX from 'xlsx';
export interface RawTable {
fileName: string;
/** 表头(去空白后的字符串) */
header: string[];
/** 数据行(已剥掉表头),每格是字符串或数字 */
rows: Array<Array<string | number>>;
}
/** ZIP 魔数 PK\x03\x04 → Excel;否则按 CSV 文本处理 */
function looksLikeZip(bytes: Uint8Array): boolean {
return bytes.length > 1 && bytes[0] === 0x50 && bytes[1] === 0x4b;
}
function splitXlsx(bytes: Uint8Array): Array<Array<unknown>> {
const wb = XLSX.read(bytes, { type: 'array', cellDates: false });
const sheetName = wb.SheetNames[0];
if (!sheetName) throw new Error('文件里没有可读的工作表');
return XLSX.utils.sheet_to_json<unknown[]>(wb.Sheets[sheetName], {
header: 1,
raw: true,
blankrows: false,
defval: '',
});
}
/** CSV 解码:严格 UTF-8,失败退 GBK */
function decodeCsv(bytes: Uint8Array): string {
const stripBom = (s: string) => (s.charCodeAt(0) === 0xfeff ? s.slice(1) : s);
try {
return stripBom(new TextDecoder('utf-8', { fatal: true }).decode(bytes));
} catch {
try {
return stripBom(new TextDecoder('gbk').decode(bytes));
} catch (err) {
throw new Error(`CSV 编码无法识别(既不是 UTF-8 也不是 GBK):${String(err)}`);
}
}
}
function splitCsvLineQuoted(line: string): string[] {
const out: string[] = [];
let cur = '';
let inQuote = false;
for (let i = 0; i < line.length; i += 1) {
const ch = line[i];
if (inQuote) {
if (ch === '"') {
if (line[i + 1] === '"') {
cur += '"';
i += 1;
} else {
inQuote = false;
}
} else cur += ch;
} else if (ch === '"') {
inQuote = true;
} else if (ch === ',') {
out.push(cur);
cur = '';
} else cur += ch;
}
out.push(cur);
return out;
}
function splitCsv(text: string): string[][] {
const lines = text.split(/\r?\n/);
const rows: string[][] = [];
let w = 0;
const hasQuote = text.indexOf('"') >= 0;
for (let i = 0; i < lines.length; i += 1) {
const line = lines[i];
if (!line) continue;
rows[w++] = hasQuote ? splitCsvLineQuoted(line) : line.split(',');
}
rows.length = w;
return rows;
}
/**
* 解码一份出险数据文件为 RawTable。
* @param fileName 用于判断后缀(.xlsx/.xls 走 SheetJS,否则按 CSV)
* @param bytes 文件原始字节(Uint8Array 或 ArrayBuffer 均可)
*/
export function decodeIncidentFile(fileName: string, bytes: Uint8Array | ArrayBuffer): RawTable {
const view = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
const isExcel = /\.xlsx$/i.test(fileName) || /\.xls$/i.test(fileName) || looksLikeZip(view);
const raw = isExcel ? splitXlsx(view) : splitCsv(decodeCsv(view));
if (raw.length < 2) throw new Error('文件里只有表头或完全是空的');
const header = raw[0].map((v) => String(v ?? '').trim());
const rows: Array<Array<string | number>> = raw
.slice(1)
.map((r) => r.map((v) => (typeof v === 'string' || typeof v === 'number' ? v : String(v ?? ''))));
return { fileName, header, rows };
}