我必须将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中的逗号不是“生成”一个新单元格,而是在主厨客户端中呢?
答案 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>""