将 DataTable 转换为 CSV 的最有效方法 [英] Most efficient way of converting a DataTable to CSV
本文介绍了将 DataTable 转换为 CSV 的最有效方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用 DataTable,我需要将它们转换为 CSV 文件格式.我使用的大多数表都有超过 50,000 条记录,因此我正在努力尽量减少转换它们所需的时间.
I'm working with DataTable's and I need to convert them to a CSV file format. Most of the tables I am working with have over 50,000 records so I'm trying to minimize the time it takes to convert them.
这是我目前的方法:
public static string table_to_csv(DataTable table)
{
string file = "";
foreach (DataColumn col in table.Columns)
file = string.Concat(file, col.ColumnName, ",");
file = file.Remove(file.LastIndexOf(','), 1);
file = string.Concat(file, "
");
foreach (DataRow row in table.Rows)
{
foreach (object item in row.ItemArray)
file = string.Concat(file, item.ToString(), ",");
file = file.Remove(file.LastIndexOf(','), 1);
file = string.Concat(file, "
");
}
return file;
}
有什么办法可以提高这种方法的效率吗?欢迎您提出任何修改和想法!
Is there any way I can improve the efficiency of this method? I'm welcome to any modifications and ideas that you have!
推荐答案
使用 System.Text.StringBuilder 用于大字符串 - 这非常快.我实现了这个:
Use a System.Text.StringBuilder for huge strings - that's pretty fast. I implemented this one:
public static string DataTableToCSV(this DataTable datatable, char seperator)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < datatable.Columns.Count; i++)
{
sb.Append(datatable.Columns[i]);
if (i < datatable.Columns.Count - 1)
sb.Append(seperator);
}
sb.AppendLine();
foreach (DataRow dr in datatable.Rows)
{
for (int i = 0; i < datatable.Columns.Count; i++)
{
sb.Append(dr[i].ToString());
if (i < datatable.Columns.Count - 1)
sb.Append(seperator);
}
sb.AppendLine();
}
return sb.ToString();
}
这篇关于将 DataTable 转换为 CSV 的最有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文