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

C#导出含多语言数据CSV乱码问题求助(Visual Studio 2022)

解决C#导出多语言CSV乱码问题

问题根源

导出的CSV日语乱码,核心原因是未添加UTF-8 BOM(字节顺序标记)——Windows平台下的Excel等软件默认无法识别无BOM的UTF-8文本,导致非ASCII字符显示乱码。同时原代码存在变量错误和冗余逻辑。

修正后的代码

public static async Task<HttpResponseMessage> Run(
    [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
    ILogger log)
{
    List<List<string>> data = new List<List<string>>
    {
        new List<string> { "Name","Age","Language"},
        new List<string> { "Nagu","32", "頼もう" }
    };
    
    StringBuilder csvContent = new StringBuilder();
    foreach (var row in data)
    {
        // 处理CSV字段中的特殊字符(逗号、引号),符合RFC4180规范
        string formattedRow = string.Join(",", row.Select(field => 
            field.Contains(",") || field.Contains("\"") ? $"\"{field.Replace("\"", "\"\"")}\"" : field));
        csvContent.AppendLine(formattedRow);
    }

    // 使用带BOM的UTF-8编码
    UTF8Encoding utf8WithBom = new UTF8Encoding(true);
    byte[] preamble = utf8WithBom.GetPreamble();
    byte[] contentBytes = utf8WithBom.GetBytes(csvContent.ToString());
    
    // 合并BOM和内容字节
    byte[] finalBytes = new byte[preamble.Length + contentBytes.Length];
    Buffer.BlockCopy(preamble, 0, finalBytes, 0, preamble.Length);
    Buffer.BlockCopy(contentBytes, 0, finalBytes, preamble.Length, contentBytes.Length);

    HttpResponseMessage response = new HttpResponseMessage(System.Net.HttpStatusCode.OK);
    ByteArrayContent content = new ByteArrayContent(finalBytes);
    
    response.Content = content;
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/csv")
    {
        CharSet = "UTF-8"
    };
    response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
    {
        FileName = "output.csv"
    };

    log.LogInformation("C# HTTP trigger function processed a request.");
    return response;
}

关键修改说明

  • 添加UTF-8 BOM:用new UTF8Encoding(true)创建带BOM的编码,将BOM字节与内容字节合并,确保Windows平台软件能正确识别UTF-8编码。
  • 修复代码错误:移除未定义的csvBytes变量和无用的MemoryStream代码块。
  • 规范CSV格式:处理字段中的逗号、引号等特殊字符,避免破坏CSV结构(符合RFC4180标准)。
  • 明确响应头设置:指定Content-Type的CharSet为UTF-8,确保客户端解析编码正确。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 23:13:09