【问题标题】:How to encode a CSV File Import?如何对 CSV 文件导入进行编码?
【发布时间】:2012-02-09 09:42:19
【问题描述】:

我有这个代码:

string ABSfilePath = "";

CsvFileReader reader = null;
ABSfilePath = Server.MapPath("/myfile.csv");

try
{
    reader = new CsvFileReader(ABSfilePath);

    CsvRow myRow = new CsvRow();
    while (reader.ReadRow(myRow))
    {
        Response.Write(myRow[0].ToString()+"<br />");
    }
}
catch (Exception err)
{
    Response.Write(err.Message);
}
finally
{
    if (reader != null)
        reader.Dispose();
}

但是当我尝试导入我的文件 myfile.csv 时,一些字符被“不正确”编码,例如:

STATUA DELLA LIBERT�

那么,如何编码呢?谢谢

【问题讨论】:

  • 您是否 100% 确定在导入之前使用记事本或记事本++ 打开文件会显示正确的字符而不是上面的有趣符号?
  • 用记事本++打开我得到了STATUA DELLA LIBERT·
  • 如果 char 之前不存在,则文件编码错误,与 CSV 解析无关,而是首先以正确的格式和编码获取文件。
  • 但在 CSV 上是 STATUA DELLA LIBERTÀ(这是正确的)
  • ...这就是它应该的方式?

标签: c# file encoding csv


【解决方案1】:
reader = new CsvFileReader(ABSfilePath);

是罪魁祸首。您应该首先使用正确的编码打开一个 StreamReader(我怀疑是 UTF-8),

StreamReader MyStreamReader = new StreamReader(ABSfilePath, System.Text.Encoding.WhateverYouNeed);

然后做

reader = new CsvFileReader(MyStreamReader.BaseStream);

【讨论】:

  • 编辑了我的答案以使用MyStreamReader.BaseStream而不是MyStreamReader
  • 好的,尝试使用 MyStreamReader.BaseStream!问题仍然存在..我尝试了其他编码..
  • 不,不使用 UTF8/7/32/UNICODE... :(
  • 你应该试试System.Text.Encoding.GetEncoding("iso-8859-15"),但你真的需要知道你的数据源是哪种编码的!
  • 当您在 Excel 中另存为 CSV 时,我想您需要提供一个字符集。 (抱歉,这里没有 Excel,只有 OOo)。但如果它来自 Excel,System.Text.Encoding.GetEncoding("iso-8859-15")System.Text.Encoding.GetEncoding("iso-8859-1") 似乎是编码的不错选择。
【解决方案2】:

在您的情况下发生的情况是 CSV 的编码和您的页面 (html) 的编码不匹配...您要么确保两者都使用相同的编码,要么在读取时转换 CSV 的编码.我不知道您使用哪个类/库CsvFileReader,但最简单的方法是使用正确的编码打开 CSV,例如使用 StreamReader 而不是 ABSFilePath 作为参数...

【讨论】:

    【解决方案3】:

    您使用的是非标准类,我猜您使用的是this one。它设计得很糟糕,它不允许您以任何方式更改编码。你需要添加一个新的构造函数来解决这个问题:

        public CsvFileWriter(string filename, Encoding encoding)
            : base(filename, encoding)
        {
        }
    

    现在您可以让它读取除 utf-8 之外的其他内容。最好的方法是 Encoding.Default。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-10
      • 2020-02-12
      • 1970-01-01
      • 2013-12-12
      • 2020-12-04
      • 2010-12-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多