将DataTable覆盖到CSV的最有效的方式 [英] Most efficient way of coverting a DataTable to CSV

查看:111
本文介绍了将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.

这是我现在的方法: p>

Here is my current method:

    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, "\r\n");

        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, "\r\n");
        }

        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 用于巨大的字符串。我实现了这一个:

yes, use a System.Text.StringBuilder for huge strings. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆