Nim*_*ima 1 c# csv excel csvhelper
我正在尝试使用 csvhelper 通过遵循一些教程来创建我的 csv 文件,但我的所有数据都只写入一列中。这是我的代码:
编辑正如我从评论中了解到的,问题在于 excel 读取 csv 文件。我找到了一些解决方案,可以通过在 Excel 设置中进行一些更改来解决此问题,在这种情况下,我的问题是:是否有办法从我的代码中解决此问题,不需要对 Excel 设置进行任何更改正确读取csv文件?
public void CreateCSVFile()
{
using (var sw = new StreamWriter(@"countrylistoutput.csv"))
{
var writer = new CsvWriter(sw);
using (var dt = ExportToCSV())
{
foreach (DataColumn column in dt.Columns)
{
writer.WriteField(column.ColumnName);
}
writer.NextRecord();
foreach (DataRow row in dt.Rows)
{
for (var i = 0; i < dt.Columns.Count; i++)
{
writer.WriteField(row[i]);
}
writer.NextRecord();
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我不明白我做错了什么,如果有人能帮助我解决这个问题,我将不胜感激。
以下是我尝试提供数据的方法:
public System.Data.DataTable ExportToCSV()
{
System.Data.DataTable table = new System.Data.DataTable();
table.Columns.Add("ID", typeof(int));
table.Columns.Add("Name", typeof(string));
table.Columns.Add("Sex", typeof(string));
table.Columns.Add("Subject1", typeof(int));
table.Columns.Add("Subject2", typeof(int));
table.Columns.Add("Subject3", typeof(int));
table.Columns.Add("Subject4", typeof(int));
table.Columns.Add("Subject5", typeof(int));
table.Columns.Add("Subject6", typeof(int));
table.Rows.Add(1, "Amar", "M", 78, 59, 72, 95, 83, 77);
table.Rows.Add(2, "Mohit", "M", 76, 65, 85, 87, 72, 90);
table.Rows.Add(3, "Garima", "F", 77, 73, 83, 64, 86, 63);
table.Rows.Add(4, "jyoti", "F", 55, 77, 85, 69, 70, 86);
table.Rows.Add(5, "Avinash", "M", 87, 73, 69, 75, 67, 81);
table.Rows.Add(6, "Devesh", "M", 92, 87, 78, 73, 75, 72);
return table;
}
}
Run Code Online (Sandbox Code Playgroud)
谢谢
当 Excel 不使用逗号作为字段分隔符时会发生这种情况(这取决于 Excel 的区域设置)。sep=,针对 Excel 的具体解决方案是在文件顶部、所有标题上方添加一个特殊行。例如:
using (var streamWriter = new StreamWriter(outputFilePath))
{
streamWriter.WriteLine("sep=,"); // make Excel use comma as field separator
using (var csvWriter = new CsvWriter(streamWriter))
{
csvWriter.WriteField("field A");
csvWriter.WriteField("field B");
csvWriter.NextRecord();
}
}
Run Code Online (Sandbox Code Playgroud)
这将解决 Excel 中的问题,但会导致其他电子表格应用程序出现问题。sep=,您可以通过使该行以预期格式为条件来支持两者。这在 Web UI 中可能是这样的:

| 归档时间: |
|
| 查看次数: |
2559 次 |
| 最近记录: |