> For the complete documentation index, see [llms.txt](https://doc.duaer.com/zh/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://doc.duaer.com/zh/snippets/parse-csv-in-code-node.md).

# 在 Duaer 里解析 CSV 文字（含 GBK 乱码）

在 Duaer 里，CSV 文件用 Extract From CSV；接口返回的 CSV 文字或 GBK 编码的银行导出文件，用 Code 节点解析成一行一条。
## 先选对 Duaer 的读法

- CSV 是文件（表单上传、邮件附件、网盘下载）且是 UTF-8：直接用 [Extract from File](/zh/build/extract-from-file.md) 的 Extract From CSV，不用写代码。
- 接口返回 CSV：在 [HTTP Request](/zh/build/http-request.md) 的 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](/zh/build/code.md)，模式保持 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 在线工具

- [GBK / UTF-8 编码在线转换（CSV、TXT 乱码修复）](https://doc.duaer.com/zh/tools/gbk-utf8-converter.md)
- [CSV 转 JSON 在线转换](https://doc.duaer.com/zh/tools/csv-to-json.md)
## Questions

### Duaer 读银行导出的 CSV 中文乱码怎么办？

文件多半是 GBK 编码。在 Duaer 里用 Extract From Text File，把 File Encoding 设为 gbk，再用 Code 节点解析。

### Duaer 的 Code 节点能用 csv-parse 之类的库吗？

Duaer 的 Code 节点默认不能引入第三方库，用本页这段不依赖库的解析代码即可。

## 相关

- [在 Duaer 里用 Extract from File 读出文件](https://doc.duaer.com/zh/build/extract-from-file.md)
- [在 Duaer 里用 Code 写一小段逻辑](https://doc.duaer.com/zh/build/code.md)
- [在 Duaer 里给银行流水自动分类并按类别汇总](https://doc.duaer.com/zh/tasks/categorize-bank-statements.md)
- [在 Duaer 里把多个 Excel 表合并成一张](https://doc.duaer.com/zh/tasks/merge-excel-files.md)

