代码片段
在 Duaer 里解析 CSV 文字(含 GBK 乱码)
在 Duaer 里,CSV 文件用 Extract From CSV;接口返回的 CSV 文字或 GBK 编码的银行导出文件,用 Code 节点解析成一行一条。
先选对 Duaer 的读法
- CSV 是文件(表单上传、邮件附件、网盘下载)且是 UTF-8:直接用 Extract from File 的 Extract From CSV,不用写代码。
- 接口返回 CSV:在 HTTP Request 的 Options 里把 Response Format 设为 File,再用 Extract From CSV。
- 国内银行、旧系统导出的 CSV 常是 GBK,Extract From CSV 读出来是乱码:用 Extract From File 的 Extract From Text File,在 Options 里把 File Encoding 设为 gbk,文字在 data 字段里,再用下面的代码解析。
Duaer Code 节点解析 CSV
接 Code,模式保持 Run Once for All Items,粘贴:
function parseCsv(text, delimiter = ',') {
const rows = [];
let row = [];
let field = '';
let inQuotes = false;
for (let i = 0; i < text.length; i++) {
const c = text[i];
if (inQuotes) {
if (c === '"' && text[i + 1] === '"') { field += '"'; i++; }
else if (c === '"') inQuotes = false;
else field += c;
} else if (c === '"') inQuotes = true;
else if (c === delimiter) { row.push(field); field = ''; }
else if (c === '\n' || c === '\r') {
if (c === '\r' && text[i + 1] === '\n') i++;
row.push(field); rows.push(row); row = []; field = '';
} else field += c;
}
if (field !== '' || row.length) { row.push(field); rows.push(row); }
return rows;
}
const out = [];
for (const item of $input.all()) {
const [header, ...lines] = parseCsv(String(item.json.data).replace(/^\uFEFF/, ''));
for (const cells of lines) {
if (cells.every((v) => v === '')) continue;
out.push({ json: Object.fromEntries(header.map((h, i) => [h.trim(), cells[i] ?? ''])) });
}
}
return out;它处理引号里的逗号、换行和两个双引号转义,第一行当表头,跳过空行。分号分隔的文件把 parseCsv 的第二个参数改成 ";",制表符改成 "\t"。
常见问题
Duaer 读银行导出的 CSV 中文乱码怎么办?
文件多半是 GBK 编码。在 Duaer 里用 Extract From Text File,把 File Encoding 设为 gbk,再用 Code 节点解析。
Duaer 的 Code 节点能用 csv-parse 之类的库吗?
Duaer 的 Code 节点默认不能引入第三方库,用本页这段不依赖库的解析代码即可。
同组
节点
在 Duaer 里用 Extract from File 读出文件
在 Duaer 里,Extract from File 从 binary 上的文件读出 JSON 条目或文本。默认 Operation 是 Extract From CSV。
节点在 Duaer 里用 Code 写一小段逻辑
在 Duaer 里,Code 用 JavaScript 或 Python 处理当前条目。只改几个字段时,优先用 Edit Fields。
办公任务在 Duaer 里给银行流水自动分类并按类别汇总
在 Duaer 里上传银行流水,Duaer Judgment 按你定的类别给每笔交易归类,再导出明细和按类别的合计。
办公任务在 Duaer 里把多个 Excel 表合并成一张
在 Duaer 里一次上传多个 xlsx,逐个读出行,加上来源文件名,去重后导出一张汇总表。不用写公式,也不扣 AI 积分。