写入到csv中的中文用excel打开时显示乱码,怎么解决?

当将包含中文字符的数据写入 CSV 文件后,使用 Excel 打开时出现乱码问题,通常是由于文件编码不正确导致的。默认情况下,csv 模块使用系统的默认编码(在大多数情况下是 ASCII 或 UTF-8,但 Excel 在某些地区可能默认使用 ANSI 编码,如 GBK)。为了确保 Excel 能够正确显示中文字符,可以采取以下几种方法:

方法 1:使用 UTF-8 带 BOM 编码

Excel 在打开 UTF-8 编码的 CSV 文件时,如果没有 BOM(字节顺序标记),可能会将其识别为 ANSI 编码,从而导致乱码。通过在文件开头添加一个 BOM,可以提示 Excel 文件是 UTF-8 编码的。

 

python复制代码

import json
import csv
# 假设你的JSON数据存储在一个字符串中,或者你可以从文件中读取它
json_data = """
{
"update_time": "2025-03-21 12:55:41",
"repositories": [
{
"name": "langchain-ai /local-deep-researcher",
"url": "https://github.com/langchain-ai /local-deep-researcher",
"description": "Fully local web research and report writing assistant",
"language": "Python",
"stars": "5869",
"stars_this_week": "3100"
},
{
"name": "yuaotian /go-cursor-help",
"url": "https://github.com/yuaotian /go-cursor-help",
"description": "解决Cursor在免费订阅期间出现以下提示的问题: You've reached your trial request limit. / Too many free trial accounts used on this machine. Please upgrade to pro. We have this limit in place to prevent abuse. Please let us know if you believe this is a mistake.",
"language": "Shell",
"stars": "15944",
"stars_this_week": "2436"
}
]
}
"""
# 解析JSON数据
data = json.loads(json_data)
# 定义CSV文件的列名
csv_columns = [
"Name",
"URL",
"Description",
"Language",
"Stars",
"Stars This Week"
]
# 打开CSV文件进行写入,使用UTF-8带BOM编码
with open("repositories.csv", "w", newline='', encoding='utf-8-sig') as csv_file:
writer = csv.writer(csv_file)
# 写入列名
writer.writerow(csv_columns)
# 遍历数据并写入CSV文件
for repo in data["repositories"]:
writer.writerow([
repo.get("name", "Unknown"),
repo.get("url", "Unknown"),
repo.get("description", "No description available"),
repo.get("language", "Unknown"),
repo.get("stars", "Unknown"),
repo.get("stars_this_week", "Unknown")
])
print("CSV文件已生成。")

代码说明:

  • encoding='utf-8-sig':使用 UTF-8 带 BOM 编码。'utf-8-sig' 会在文件开头添加一个 BOM,这样 Excel 就能正确识别文件为 UTF-8 编码。

方法 2:在 Excel 中手动指定编码

如果你无法控制 CSV 文件的生成过程,或者不想修改代码,可以在 Excel 中手动指定文件的编码:

  1. 打开 Excel
  2. 选择“数据”选项卡,然后点击“从文本/CSV”。
  3. 选择你的 CSV 文件,在导入向导中,你可以手动指定文件的编码为 UTF-8。

方法 3:使用其他工具打开并另存为

你还可以使用其他工具(如 Notepad++、Sublime Text 或 Visual Studio Code)打开 CSV 文件,并确保其编码为 UTF-8,然后另存为 CSV 文件。之后再用 Excel 打开。

总结

  • 推荐方法:使用 UTF-8 带 BOM 编码(encoding='utf-8-sig')是最简单且有效的方法,可以确保 Excel 正确显示中文字符。
  • 其他方法:如果无法修改代码,可以在 Excel 中手动指定编码,或使用其他工具调整文件编码。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值