CSV encoding issues (Microsoft Excel)

后端 未结 3 606
一生所求
一生所求 2021-01-04 23:42

I am dynamically creating CSV files using C#, and I am encountering some strange encoding issues. I currently use the ASCII encoding, which works fine in Excel 2010, which I

相关标签:
3条回答
  • 2021-01-05 00:18

    I'm using Windows ANSI codepage 1252 without any problems on Excel 2003. I explicitly changed to this because of the same issue you are seeing.

    private const int WIN_1252_CP = 1252; // Windows ANSI codepage 1252
    
    this._writer = new StreamWriter(fileName, false, Encoding.GetEncoding(WIN_1252_CP));
    
    0 讨论(0)
  • 2021-01-05 00:25

    I've successfully used UTF8 encoding when writing CSV files intended to work with Excel.

    The only problem I had was making sure to use the overload of the StreamWriter constructor that takes an encoding as a parameter. The default encoding of StreamWriter says it is UTF8 but it's really UTF8-Without-A-Byte-Order-Mark and without a BOM Excel will mess up characters using multiple bytes.

    0 讨论(0)
  • 2021-01-05 00:28

    You need to add Preamble to file:

            var data = Encoding.UTF8.GetBytes(csv);
            var result = Encoding.UTF8.GetPreamble().Concat(data).ToArray();
            return File(new MemoryStream(result), "application/octet-stream", "file.csv");
    
    0 讨论(0)
提交回复
热议问题