在 C# 中读取 CSV 文件

我有以下代码可以导入 excel 文档并对其进行解析,以便在将数据保存到数据库之前对其进行操作。

我可以很好地解析 .xlsx 和 .xls 文件,但无法弄清楚如何将现有代码用于 .csv 文件

我工作的客户想要使用 .csv 文件类型来接受特殊字符。

OpenFileDialog opener = new OpenFileDialog();
opener.Filter = "Excel Files| *.xlsx;*.xls;*.csv;";
if (opener.ShowDialog() == DialogResult.Cancel)
    return;

FileStream streamer = new FileStream(opener.FileName, FileMode.Open);
IExcelDataReader reader;
if (Path.GetExtension(opener.FileName) == ".xls")
{
    reader = ExcelReaderFactory.CreateBinaryReader(streamer);
}
else if (Path.GetExtension(opener.FileName) == ".csv")
{

    *** Need Something Here to read CSV Files that will work with 
        the rest of code***
}
else
{
    reader = ExcelReaderFactory.CreateOpenXmlReader(streamer);
}
DataSet results = reader.AsDataSet();
results.Tables[0].Rows[0].Delete();
results.AcceptChanges();

foreach (System.Data.DataTable table in results.Tables)
{
    foreach (DataRow dr in table.Rows)
    {
       >>> Do Something With the Data
    }
}
stack overflow Read CSV files in C#
原文答案

答案:

作者头像
private void ReadCSVFile(string filepath)
{
    //receiverList = new List<ReceiverUser>();

    try
    {
        if (filepath == string.Empty)
            return;

        using (StreamReader sr = new StreamReader(FileUpload1.PostedFile.InputStream))
        {
            string line;

            while ((line = sr.ReadLine()) != null)
            {
                SplitLine(line);
            }
        }

        #region row add test
        DataTable dt = new DataTable();

        if (dt.Columns.Count == 0)
        {
            dt.Columns.Add("Name", typeof(string));
            dt.Columns.Add("Mail", typeof(string));
            dt.Columns.Add("Amount", typeof(double));
        }

        DataRow NewRow;
/*
        foreach (var item in receiverList)
        {
            NewRow = dt.NewRow();
            NewRow[0] = item.Name + " " + item.Surname;
            NewRow[1] = item.Mail;
            NewRow[2] = item.Amount;
            dt.Rows.Add(NewRow);
        }
*/

        grdRec.DataSource = dt;
        grdRec.DataBind();

        #endregion
    }
    catch (Exception)
    {

    }

}//end of function

该函数读取一个 CSV 文件,将参数加载到 Datatable 并将网格的数据源设置为 Datatable。这是一个 ASP.NET WebfoRM 代码。

作者头像

假设您的 IExcelDataReader 是一个读取 Excel 文件的第三方软件包(一个相当安全的选择)并且它本身不能处理 CSV(我不确定那部分),那么您总是可以完全单独处理 CSV。

OLE 有一个不错的 CSV 阅读器,所以这样的东西应该可以工作。

List<DataTable> tables = new List<DataTable>();

if (Path.GetExtension(opener.FileName) == ".csv")
{
    OleDbConnection conn = new OleDbConnection(string.Format(
        @"Provider=Microsoft.Jet.OleDb.4.0; Data Source={0};" +
        "Extended Properties="Text;HDR=YES;FMT=Delimited"",
        opener.FileName
    ));
    conn.Open();

    string sql = string.Format("select * from [{0}]", Path.GetFileName(opener.FileName));
    OleDbCommand cmd = new OleDbCommand(sql, conn);
    OleDbDataReader reader = cmd.ExecuteReader();

    DataTable dt = new DataTable();
    dt.Load(reader);
    tables.Add(dt);

    reader.Close();
}
else
{
    FileStream streamer = new FileStream(opener.FileName, FileMode.Open);
    IExcelDataReader reader = null;
    if (Path.GetExtension(opener.FileName) == ".xls")
        reader = ExcelReaderFactory.CreateBinaryReader(streamer);
    else
        reader = ExcelReaderFactory.CreateOpenXmlReader(streamer);
    DataSet results = reader.AsDataSet();
    results.Tables[0].Rows[0].Delete();
    results.AcceptChanges();

    foreach (DataTable table in results.Tables)
        tables.Add(table);
}

然后只需引用您的本地数据表列表 ( tables ) 而不是 Results.Tables, ,因为它现在本地范围为 IExcelReader

foreach (System.Data.DataTable table in tables)
{
    foreach (DataRow dr in table.Rows)
    {
       >>> Do Something With the Data
    }
}

如果由于某种原因不能使用 OLE,.NET 类库实际上有一个 CSV 解析器。在我看来,它隐藏得很好,但很好:

http://odedcoster.com/blog/2012/03/28/did-you-know-a-net-csv-parser-that-comes-with-visual-studio/

作者头像

你能检查下面的代码吗?这将对您有用。

 OpenFileDialog opener = new OpenFileDialog();
   opener.Filter = "Excel Files| *.xlsx;*.xls;*.csv;";
if (opener.ShowDialog() == DialogResult.Cancel)
    return;

FileStream streamer = new FileStream(opener.FileName, FileMode.Open);
IExcelDataReader reader;
if (Path.GetExtension(opener.FileName) == ".xls")
{
    reader = ExcelReaderFactory.CreateBinaryReader(streamer);
}
else if (Path.GetExtension(opener.FileName) == ".csv")
{

   var reader = ExcelReaderFactory.CreateReader(stream, new ExcelReaderConfiguration() {

// Gets or sets the encoding to use when the input XLS lacks a CodePage
// record, or when the input CSV lacks a BOM and does not parse as UTF8. 
// Default: cp1252. (XLS BIFF2-5 and CSV only)
FallbackEncoding = Encoding.GetEncoding(1252),

// Gets or sets the password used to open password protected workbooks.
Password = "password",

// Gets or sets an array of CSV separator candidates. The reader 
// autodetects which best fits the input data. Default: , ; TAB | # 
// (CSV only)
AutodetectSeparators = new char[] { ',', ';', 't', '|', '#' };
});
    }
    else
    {
        reader = ExcelReaderFactory.CreateOpenXmlReader(streamer);
    }
    DataSet results = reader.AsDataSet();
    results.Tables[0].Rows[0].Delete();
    results.AcceptChanges();

    foreach (System.Data.DataTable table in results.Tables)
    {
        foreach (DataRow dr in table.Rows)
        {
           >>> Do Something With the Data
        }
    }

参考这个链接 ExcelDataReader

作者头像

您可以使用 CSVHelper 来避免手动编写 CVS 解析器