逗号和逗号之间有什么区别?

时间:2016-01-25 13:37:40

标签: c# datatable export-to-csv

我必须将DataTable的内容保存到CSV文件中。在DataTable一切正常,数据来自SQL查询。但是,如果我在CSV中打开Excel,我可以看到:

+---------------------+---------------------+------------------------------+------+------+----+
|    DisplayName0     |     Publisher0      |             col3             | col4 | col5 |    |
+---------------------+---------------------+------------------------------+------+------+----+
| Dropbox             | Dropbox, Inc.       | 432                          |  415 |   17 |    |
| Chef Client v12.4.3 | Chef Software       | Inc. <maintainers@chef.io>"" |  193 |  180 | 13 |
| Cisco AnyConnect    | Cisco Systems, Inc. | 836                          |  824 |   12 |    |
+---------------------+---------------------+------------------------------+------+------+----+
'Dropbox, Inc.' -> 'Dropbox, Inc.' //this is good
'Cisco Systems, Inc.' -> 'Cisco Systems, Inc.' //this is good too
'"Chef Software, Inc. <maintainers@chef.io>"' -> 'Chef Software' and ' Inc. <maintainers@chef.io>""' //what happened here?

用于将DataTable导出到CSV的旧代码是:

System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(dlg3.FileName);

string strHeader = "";
for (int s = 0; s < tbl.Columns.Count; s++)
{
    strHeader += "\"" + tbl.Columns[s].ColumnName + "\",";
}
streamWriter.WriteLine(strHeader);

for (int m = 0; m < tbl.Rows.Count; m++)
{
    string strRowValue = "";
    for (int n = 0; n < tbl.Columns.Count; n++)
    {
        if (tbl.Rows[m][n].ToString() != "")
        {
            strRowValue += "\"" + tbl.Rows[m][n] + "\",";
        }
        else
        {
            strRowValue += tbl.Rows[m][n] + ",";
        }
    }
    streamWriter.WriteLine(strRowValue);
}
streamWriter.Close();

所以问题是为什么dropbox中的逗号不是“生成”一个新单元格,而是在主厨客户端中呢?

2 个答案:

答案 0 :(得分:4)

字符串的和平被双重引用。 在添加之前,您可以检查字符串是否已经开始并以引号结束。

if(!tbl.Rows[m][n].StartsWith("\"") && !tbl.Rows[m][n].EndsWith("\""))
strRowValue += tbl.Rows[m][n] + ",";
else
strRowValue += "\"" + tbl.Rows[m][n] + "\",";

答案 1 :(得分:3)

问题数据后面有双引号:“”

看起来您的数据中可能有引号,然后在输出数据时添加引号,因此您最终会在文件中添加引号:

""Chef Software, Inc. <maintainers@chef.io>""
相关问题