xlsx-to-raw-csv.mjs
8.42 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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
#!/usr/bin/env node
/**
* 把业务方给的原始表格(.xlsx)转成离线管线认的那份 CSV:data/raw/incidents.sample.csv。
*
* 为什么要有这一步(而不是把 xlsx 直接喂给 preprocess.mjs):
* 内置数据的管线(preprocess.mjs)读的是**行式 CSV**,它按 ',' 切列、按位置取字段,
* 图的是首屏那三个 JSON 产物可复现、可 diff。而浏览器导入那条路(ingestCore.ts)
* 才支持 xlsx。两条路必须吃同一份表格才能对账(ingestArtifacts.test.ts 盯的就是这件事),
* 所以换内置数据时统一在这里落成 CSV,xlsx 只作为来源、不进管线。
*
* 三个转换细节,每一个都会让数据静默变味,所以都做了显式处理:
*
* 1) 报案时间是 Excel 日期序列号(例如 46284.6379166667),不是字符串。
* 按 1900 日历(序列号 − 25569 天)折算成 UTC 壁钟再打成 'YYYY-MM-DD HH:mm:ss',
* 与 preprocess/ingestCore 认的写法一致;表格里若混着文本时间,原样透传。
* 注意不能按本机时区换算:那是「Excel 里显示出来的那一刻」,跟着机器跑就会整体偏移。
*
* 2) 经纬度在源表里是文本,且带着浮点尾巴(114.31331899999998 这种)。
* 统一按 6 位小数归一(管线存的就是 lng×1e6 的整数,6 位小数与它一一对应,
* 不多不少:既抹掉浮点噪声,也不改变任何一个入库坐标)。
*
* 3) 地址里有半角逗号(「龙平西路南侧,龙福路以北」这类),CSV 必须加引号包住。
* 下游两条流水线都认 RFC4180 的引号写法(preprocess 里见 splitLine、
* ingestCore 里见 splitCsvLineQuoted),所以这里不删逗号、不改一个字:
* 改标点等于改数据,而这份表是要拿去和原始表格逐行核对的。
*
* 用法:node scripts/xlsx-to-raw-csv.mjs <原始表格.xlsx> [--out=<路径>]
* 然后跑 node scripts/preprocess.mjs 重生成 public/data/*.json
*/
import fs from 'node:fs';
import path from 'node:path';
import { createRequire } from 'node:module';
import { fileURLToPath } from 'node:url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(__dirname, '..');
const OUT_CSV = path.join(ROOT, 'data/raw/incidents.sample.csv');
const HEADER = ['案件号', '出险地点', '报案时间', '经度', '纬度'];
const args = process.argv.slice(2);
const srcArg = args.find((a) => !a.startsWith('--'));
const outArg = args.find((a) => a.startsWith('--out='));
const OUT = outArg ? path.resolve(ROOT, outArg.slice('--out='.length)) : OUT_CSV;
if (!srcArg) {
console.error('用法:node scripts/xlsx-to-raw-csv.mjs <原始表格.xlsx> [--out=<路径>]');
process.exit(1);
}
const SRC = path.resolve(srcArg);
if (!fs.existsSync(SRC)) {
console.error(`[csv] 找不到源表格:${SRC}`);
process.exit(1);
}
// xlsx 是项目依赖(浏览器导入也用同一个包),从 node_modules 直接取,不额外装东西
const require = createRequire(import.meta.url);
const XLSX = require('xlsx');
/**
* Excel 序列号 → 'YYYY-MM-DD HH:mm:ss'。
*
* 25569 = 1899-12-30 到 1900-01-01 那套 1900 日历下「序列号 1」对应的天数差(含 Excel 那个
* 不存在的 1900-02-29 的偏移)。全程用 UTC 取值器:壁钟照抄,不受本机时区影响。
* 源表 WorkbookProps.date1904 为 false(1900 日历),换表时若这一项变成 true 需要另加 1462 天。
*/
function serialToText(v) {
const ms = Math.round((v - 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(Math.floor(d.getUTCSeconds()))}`
);
}
/** 6 位小数:与产物里的 lng/lat×1e6 整数一一对应,只抹浮点噪声,不移动任何一个点 */
function coordText(v) {
const n = Number(v);
if (!Number.isFinite(n)) return String(v).trim();
return n.toFixed(6);
}
/** CSV 引号规则:含逗号、引号、换行的字段才加引号,其余原样(模版数据大多不加,读起来也干净) */
function field(s) {
const t = String(s);
return /[",\n\r]/.test(t) ? `"${t.replace(/"/g, '""')}"` : t;
}
const wb = XLSX.readFile(SRC, { cellDates: false });
const sheetName = wb.SheetNames[0];
const date1904 = !!wb.Workbook?.WBProps?.date1904;
if (date1904) {
console.error('[csv] 这份表用的是 1900 之外的另一套日历(date1904),序列号换算要先调整,已终止');
process.exit(1);
}
const rows = XLSX.utils.sheet_to_json(wb.Sheets[sheetName], {
header: 1,
raw: true,
defval: '',
});
if (!rows.length) {
console.error(`[csv] 工作表「${sheetName}」是空的`);
process.exit(1);
}
// 表头按位置认,不按名字猜:源表列序若与模板不同,必须在这里拦下来,
// 而不是让下游把经纬度当时间解析、把整列地址读成空
const head = rows[0].map((c) => String(c).trim());
if (head.join(',') !== HEADER.join(',')) {
console.error(
`[csv] 表头与模板不一致:\n 期望 ${HEADER.join(',')}\n 实到 ${head.join(',')}\n` +
' 请先在源表里按模板列序整理,再重跑本脚本(列名对不上时绝不猜)',
);
process.exit(1);
}
const lines = [HEADER.join(',')];
const report = {
数据行: 0,
空行跳过: 0,
字段数不为5: 0,
案件号非纯数字: 0,
时间按文本透传: 0,
坐标非数值: 0,
};
const problems = [];
const seenCaseNo = new Map();
let dup = 0;
let tsMin = Infinity;
let tsMax = -Infinity;
for (let i = 1; i < rows.length; i += 1) {
const r = rows[i];
if (!r || r.every((c) => c === '' || c === null || c === undefined)) {
report.空行跳过 += 1;
continue;
}
if (r.length !== 5) {
report.字段数不为5 += 1;
if (problems.length < 5) problems.push(`第 ${i + 1} 行有 ${r.length} 列:${JSON.stringify(r)}`);
continue;
}
const [caseNoRaw, address, time, lngRaw, latRaw] = r;
const caseNo = String(caseNoRaw).trim();
if (!/^\d{15,24}$/.test(caseNo)) {
report.案件号非纯数字 += 1;
if (problems.length < 5) problems.push(`第 ${i + 1} 行案件号不成样:${caseNo}`);
continue;
}
const prevLine = seenCaseNo.get(caseNo);
if (prevLine !== undefined) {
dup += 1;
if (problems.length < 5) problems.push(`第 ${i + 1} 行案件号与第 ${prevLine} 行重复:${caseNo}`);
} else {
seenCaseNo.set(caseNo, i + 1);
}
let timeText;
if (typeof time === 'number' && Number.isFinite(time)) {
timeText = serialToText(time);
} else {
timeText = String(time).trim();
report.时间按文本透传 += 1;
}
if (!timeText) {
report.坐标非数值 += 1;
if (problems.length < 5) problems.push(`第 ${i + 1} 行报案时间为空`);
continue;
}
const lng = Number(lngRaw);
const lat = Number(latRaw);
if (!Number.isFinite(lng) || !Number.isFinite(lat)) {
report.坐标非数值 += 1;
if (problems.length < 5)
problems.push(`第 ${i + 1} 行经纬度读不出数:${JSON.stringify([lngRaw, latRaw])}`);
continue;
}
report.数据行 += 1;
// 时间排序性只用来打报告:管线自己按 min/max 收范围,这里不改任何行序
const epoch = Date.parse(timeText.replace(/\//g, '-').replace(' ', 'T') + '+08:00');
if (Number.isFinite(epoch)) {
if (epoch < tsMin) tsMin = epoch;
if (epoch > tsMax) tsMax = epoch;
}
lines.push([field(caseNo), field(String(address).trim()), field(timeText), coordText(lng), coordText(lat)].join(','));
}
fs.writeFileSync(OUT, lines.join('\n') + '\n', 'utf8');
const rel = path.relative(ROOT, OUT);
console.log(`[csv] 来源:${path.basename(SRC)}(工作表「${sheetName}」)`);
console.log(`[csv] 写出:${rel},${report.数据行} 行 + 表头`);
console.table(report);
if (dup) console.warn(`[csv] ⚠️ 案件号重复 ${dup} 处:内置管线不去重,这些行会各自计入起数`);
if (problems.length) {
console.warn('[csv] 需要人工确认的样本:');
for (const p of problems) console.warn(' · ' + p);
}
if (Number.isFinite(tsMin) && Number.isFinite(tsMax)) {
const f = (ms) => new Date(ms + 8 * 3600 * 1000).toISOString().slice(0, 19).replace('T', ' ');
console.log(`[csv] 报案时间跨度(北京时间):${f(tsMin)} — ${f(tsMax)}`);
}
console.log('[csv] 下一步:node scripts/preprocess.mjs 重生成 public/data/*.json');