table-store.ts
1.94 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
/** 按扩展名分派 CSV 与 Excel 读写;补齐逻辑只看文本矩阵,不关心载体格式。 */
import path from 'node:path';
import { atomicCsv, readCsv } from './csv-store.ts';
import { blankSheet, isExcel, readExcel, writeExcel } from './excel-store.ts';
import type { ExcelSheet } from './excel-store.ts';
import { UserError } from './errors.ts';
import { TARGET_COLUMNS } from './targets.ts';
export type Table = {
header: string[];
rows: string[][];
sheet: ExcelSheet | null;
/** 模板常缺三个补全列:读取时自动在末尾追加空列,这里记录追加了哪些。 */
appended: string[];
};
export function readTable(file: string, limit: number | null): Table {
const table = isExcel(file)
? readExcel(file, limit)
: { ...readCsv(file, limit), sheet: null };
const appended = TARGET_COLUMNS.filter((name) => !table.header.includes(name));
if (appended.length > 0) {
table.header.push(...appended);
table.rows.forEach((row) => row.push(...appended.map(() => '')));
}
return { ...table, appended };
}
/** 输出格式由目标文件扩展名决定,允许 Excel 进出与 CSV 互换。 */
export function writeTable(file: string, table: Table): void {
if (path.extname(file).toLowerCase() === '.csv') {
atomicCsv(file, table.header, table.rows);
return;
}
if (!isExcel(file)) throw new UserError(`无法识别的输出格式:${path.extname(file)}`);
writeExcel(file, table.header, table.rows, table.sheet ?? blankSheet(table.header, table.rows));
}
/** 行序变化时同步搬移 Excel 单元格对象,保证写回的是整行原值而不是纯文本。 */
export function permuteTable(table: Table, order: readonly number[]): void {
const sheet = table.sheet;
table.rows = order.map((position) => table.rows[position]);
if (sheet !== null) {
sheet.cells = order.map((position) => sheet.cells[position]);
sheet.rowNumbers = order.map((position) => sheet.rowNumbers[position]);
}
}