import-xlsx.mjs
3.73 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
#!/usr/bin/env node
/**
* 把「深圳车险出险位置」Excel 转成 preprocess 契约需要的 CSV。
*
* 契约(scripts/preprocess.mjs):5 列、顺序固定为
* 案件号, 出险地点, 报案时间, 经度, 纬度
* 其中:
* - 案件号 / 出险地点 / 经度 / 纬度 在 Excel 里已是文本,原样过(案件号 20 位长整数,
* 文本型保存,不会像数值型那样被 Excel 砍到 15 位有效数字)。
* - 报案时间在 Excel 里是序列号数字(t=n),这里统一换算成深圳本地墙钟
* "YYYY-MM-DD HH:mm:ss";preprocess 再把它拼成 "...+08:00",时区不重算、不漂移。
*
* 用法:node scripts/import-xlsx.mjs [xlsx路径]
* 默认源:C:/Users/Limin/Desktop/深圳车险出险位置-9月.xlsx
* 输出:data/raw/incidents.sample.csv(覆盖;旧文件先备份为 .bak)
*/
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import XLSX from 'xlsx';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(__dirname, '..');
const SRC = process.argv[2] || 'C:/Users/Limin/Desktop/深圳车险出险位置-9月.xlsx';
const OUT = path.join(ROOT, 'data/raw/incidents.sample.csv');
/**
* Excel 序列号 → 深圳本地墙钟字符串。
* 25569 = 1899-12-30(Excel 纪元,已含 1900 闰年 bug 修正)到 1970-01-01 的天数,
* 2026 年数据适用。换算出的 Date 用 UTC 字段读回,得到的就是表格里的墙钟,
* 再交给 preprocess 拼 +08:00,时区不会重复计算。
*/
function serialToWallClock(serial) {
const ms = (serial - 25569) * 86400000;
const d = new Date(ms);
const p = (n) => String(n).padStart(2, '0');
return `${d.getUTCFullYear()}-${p(d.getUTCMonth() + 1)}-${p(d.getUTCDate())} ${p(
d.getUTCHours(),
)}:${p(d.getUTCMinutes())}:${p(d.getUTCSeconds())}`;
}
/** CSV 字段转义:含逗号 / 引号 / 换行时整段加引号,内部引号翻倍 */
function csvField(val) {
const str = val == null ? '' : String(val);
if (/[",\n\r]/.test(str)) return '"' + str.replace(/"/g, '""') + '"';
return str;
}
const wb = XLSX.readFile(SRC);
const ws = wb.Sheets[wb.SheetNames[0]];
const rows = XLSX.utils.sheet_to_json(ws, { header: 1, raw: true, defval: '' });
const header = rows[0];
const colIdx = {};
header.forEach((h, i) => {
colIdx[String(h).trim()] = i;
});
const iCase = colIdx['案件号'];
const iAddr = colIdx['出险地点'];
const iTime = colIdx['报案时间'];
const iLng = colIdx['经度'];
const iLat = colIdx['纬度'];
if ([iCase, iAddr, iTime, iLng, iLat].some((i) => i === undefined)) {
console.error('[import-xlsx] 表头缺少必要列,当前表头:', JSON.stringify(header));
process.exit(1);
}
let written = 0;
let skipped = 0;
const lines = ['案件号,出险地点,报案时间,经度,纬度'];
for (let r = 1; r < rows.length; r += 1) {
const row = rows[r];
if (!row || row.length === 0) continue;
const caseNo = row[iCase];
const addr = row[iAddr];
const timeRaw = row[iTime];
const lng = row[iLng];
const lat = row[iLat];
if (caseNo === '' || addr === '' || timeRaw === '' || lng === '' || lat === '') {
skipped += 1;
continue;
}
const timeStr =
typeof timeRaw === 'number' ? serialToWallClock(timeRaw) : String(timeRaw).trim();
lines.push(
[csvField(caseNo), csvField(addr), csvField(timeStr), csvField(lng), csvField(lat)].join(','),
);
written += 1;
}
fs.mkdirSync(path.dirname(OUT), { recursive: true });
if (fs.existsSync(OUT)) fs.copyFileSync(OUT, OUT + '.bak');
fs.writeFileSync(OUT, lines.join('\n') + '\n', 'utf8');
console.log(
`[import-xlsx] 写入 ${written} 行,跳过 ${skipped} 行空行 → ${path.relative(ROOT, OUT)}(旧文件已备份为 .bak)`,
);