You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js使用fast-csv写入CSV文件时特殊字符乱码如何解决

问题原因

你遇到的是典型的编码识别不匹配问题:你看到的Ä对应Ä、ö对应ö的乱码,本质是fast-csv默认输出的无BOM UTF-8文件,被Windows平台的Excel等工具错误按Latin-1(ISO-8859-1,德语区ANSI默认编码)解码导致的。

解决方案

推荐方案:写入带BOM的UTF-8文件

该方案兼容性最强,支持所有语言字符,适配绝大多数办公软件的读取规则,只需要在writeToPath的配置项中新增两个参数即可:

import { writeToPath } from "fast-csv";

const data = [
  {
    "name": "Ästhetik Zahnarzt Hamburg City Z-24 Mö 17 / Dr. P. Michaelis, Dr. C. Khorram",
    "street_number": "Speersort 8",
    "zip_location": "20095 Hamburg, City Innenstadt",
    "phone": "040 34 45 44",
    "website": "http://www.z-24.de",
    "area": "Branche: Zahnärzte"
  }
]

writeToPath("tmp.csv", data, { 
  headers: true,
  // 自动在文件开头写入UTF-8 BOM头,让Windows工具正确识别编码
  writeBOM: true,
  encoding: 'utf8'
})
  .on("error", (err) => console.error(err))
  .on("finish", () => console.log("Done writing."));

修改后生成的文件用系统记事本打开验证,特殊字符显示正常即配置生效,用Excel打开也不会出现乱码。

备选方案:输出Latin-1编码文件

如果你的使用场景需要适配仅支持Latin-1编码的老系统,可以直接指定输出编码为latin1:

writeToPath("tmp.csv", data, { 
  headers: true,
  encoding: 'latin1'
})

注意:该编码仅支持西欧语系字符,若数据中包含中文、西里尔文等其他语系字符会出现丢失,仅在特定场景使用。

内容的提问来源于stack exchange,提问作者Wrath

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 12:45:11