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

如何修复Python生成CSV文件时的编码乱码问题

解决CSV报表乱码问题

CSV打开乱码的核心原因是编码不匹配,尤其是Windows系统下的Excel默认不会自动识别无BOM的UTF-8编码。以下是针对你这段Django代码的修复方案:

修复步骤

  • 给HTTP响应指定UTF-8编码,并添加UTF-8 BOM(字节顺序标记),让Excel能正确识别编码
  • 明确设置Content-Type的字符集

修改后的完整代码

import csv
from django.http import HttpResponse

def download_report(request, date):
    food_orders = FoodOrder.objects.filter(order__date__date=date)

    # 指定UTF-8编码,并设置响应头
    response = HttpResponse(
        content_type="text/csv; charset=utf-8",
        headers={"Content-Disposition": 'attachment; filename="report.csv"'}
    )
    # 写入UTF-8 BOM,解决Excel识别编码的问题
    response.write('\ufeff')

    writer = csv.writer(response)
    writer.writerow([date])

    total_cost_of_all_orders = 0

    for order in food_orders:
        order_time = order.order.date.strftime('%H:%M')
        customer_name = order.order.employee.name
        dishes = '; '.join([str(dish) for dish in order.food.all()])
        order_cost = order.total_cost

        writer.writerow([f'Time: {order_time}, Name: {customer_name}, Food: {dishes}, Cost: {order_cost} rub.'])

        total_cost_of_all_orders += order_cost

    writer.writerow(['', '', '', 'Total cost of day:', total_cost_of_all_orders])

    return response

关键改动说明

  1. Content-Type添加charset=utf-8:明确告知浏览器和Excel文件使用UTF-8编码,避免默认用系统编码解析
  2. 写入UTF-8 BOM:response.write('\ufeff') 在文件开头写入BOM标记,Excel读取时会自动识别这是UTF-8编码,彻底解决乱码问题
  3. 原有业务逻辑完全保留,仅调整编码相关设置

如果是用其他文本编辑器打开乱码,只需确保编辑器切换到UTF-8编码模式即可,上述方案主要针对Excel的兼容性问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 04:30:04