【问题标题】:Set "NULL" in Empty cells in CsvReader在 CsvReader 的空单元格中设置“NULL”
【发布时间】:2014-01-27 12:36:43
【问题描述】:

这是我的代码:

using (System.Net.WebResponse tmpRes = tmpReq.GetResponse())
{
    using (System.IO.Stream tmpStream = tmpRes.GetResponseStream())
    {
        using (System.IO.TextReader tmpReader = new System.IO.StreamReader(tmpStream))
        {
            string fileContents = tmpReader.ReadToEnd();
            for (int i = 0; i < fileContents.Length; i++)
            {
                if (fileContents[i] == "")
                {
                    fileContents[i] = "null";
                }
            }
            using (Stream s = GenerateStreamFromString(fileContents))
            {}
       }
    }
} 

这显示错误 'string' 到 'char' 隐式转换。有没有其他方法可以在 CSVReader 的空字段中设置 "NULL"

【问题讨论】:

  • 你在哪里使用CSVReader
  • 还有一些 CSVReader - 你用的是哪一个?
  • 从 ftpwebrequest 读取 CSV

标签: c# asp.net asp.net-mvc csv


【解决方案1】:

您根本没有使用CsvReader。您也没有通过分隔符拆分字符串以获得“单元格”。但是,您可以从 CsvReader 加载 DataTable 并对其进行修改。

这是一个假设制表符作为分隔符的示例:

var tblCSV = new DataTable();
using (System.Net.WebResponse tmpRes = tmpReq.GetResponse())
using (System.IO.Stream tmpStream = tmpRes.GetResponseStream())
using (System.IO.TextReader tmpReader = new System.IO.StreamReader(tmpStream))
using (var csv = new CsvReader(tmpReader, true, '\t', '"', '\0', '\0', ValueTrimmingOptions.All))
{
    csv.MissingFieldAction = MissingFieldAction.ParseError;
    csv.DefaultParseErrorAction = ParseErrorAction.RaiseEvent;
    csv.ParseError += csv_ParseError;
    csv.SkipEmptyLines = true;
    // load into DataTable
    tblCSV.Load(csv, LoadOption.OverwriteChanges, csvTable_FillError);
} 

现在循环行和列并相应地修改它们:

foreach(DataRow row in tblCSV.Rows)
{
    foreach(DataColumn col in tblCSV.Columns)
    {
        if(string.IsNullOrWhiteSpace(row.Field<string>(col)))
            row.SetField(col, "null");
    }
}

更新与您的评论相关:

我想在 csv 时在 sql 数据库的空单元格中添加 NULL 值 数据保存在数据库中。有没有其他办法?

您可以简单地使用上面的循环来更新您的表格:

using (var con = new SqlConnection("ConnectionString"))
{
    con.Open();
    foreach (DataRow row in tblCSV.Rows)
    {
        using (var cmd = new SqlCommand("INSERT INTO table(Col1,Col2) VALUES (@Col1,Col2);", con))
        {
            string col1 = row.Field<string>("Col1");
            if (string.IsNullOrWhiteSpace(col1))
                col1 = null;
            string col2 = row.Field<string>("Col2");
            if (string.IsNullOrWhiteSpace(col2))
                col2 = null;
            cmd.Parameters.AddWithValue("@col1", col1);
            cmd.Parameters.AddWithValue("@col2", col2);
            int inserted = cmd.ExecuteNonQuery();
        }
    }
}

【讨论】:

  • 当 csv 数据保存在数据库中时,我想在 sql 数据库的空单元格中添加 NULL 值。有没有其他方法,谢谢回答
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-08
  • 1970-01-01
  • 1970-01-01
  • 2017-03-01
  • 1970-01-01
  • 2012-08-26
相关资源
最近更新 更多