是否有任何形式的声明将数据行转换为CSV行,以便将其写入.csv文件? (有或没有介于两者之间的步骤)
答案 0 :(得分:3)
尝试使用以下代码:
StringBuilder sb = new StringBuilder();
var columnNames = dt.Columns.Cast<DataColumn>().Select(column => column.ColumnName).ToArray();
sb.AppendLine(string.Join(",", columnNames));
foreach (DataRow row in dt.Rows)
{
var fields = row.ItemArray.Select(field => field.ToString()).ToArray();
sb.AppendLine(string.Join(",", fields));
}
File.WriteAllText("test.csv", sb.ToString());
答案 1 :(得分:0)
谷歌的快速搜索将其转变为: http://www.rcs-solutions.com/blog/2009/01/15/ConvertDataTableToCSVViaExtensionMethod.aspx
有点过时了。没有本地方法可以做到这一点,所以你需要使用循环结构迭代数据表,但我建议使用LINQ方法,因为它会更清晰。
答案 2 :(得分:0)
前几天我在看this:
根据快速入门,您可以编写如下代码:
[DelimitedRecord(",")]
public class Customer
{
public int CustId;
public string Name;
public decimal Balance;
}
FileHelperEngine engine = new FileHelperEngine(typeof(Customer));
Customer[] res = engine.ReadFile("FileIn.txt") as Customer[];
engine.WriteFile("FileOut.txt", res);
答案 3 :(得分:0)
以下内容适用于我。
foreach (DataRow row in rows)
{
string line = "";
for (int i = 0; i < row.ItemArray.Length; i++)
{
line += row[i] + ",";
}
line = line.TrimEnd(',');
}