使用" |"将DataTable导出为CSV文件分隔符

时间:2015-06-09 03:10:54

标签: c# asp.net csv datatable export

我正在构建一个ASP.NET C#项目,该项目具有将DataTables导出为CSV文件的功能,每个单元格具有|分隔符。我希望它看起来像这样:

100001|06/19/1861|Jose|Rizal|Filipino|Calamba, Laguna| 100002|08/30/1850|Marcelo|Del Pilar|Filipino|| 100003||||||

正如您所看到的,每个小组'由|分隔。此外,空单元格也应该具有分隔符。所有行应具有相同数量的|分隔符。

到目前为止,我有这段代码:

StringBuilder sb = new StringBuilder();
DataTable dtFile1 = file1BLO.SelectAllFile1();
foreach (DataRow dr in dtFile1.Rows)
{
      //build text file
}

3 个答案:

答案 0 :(得分:2)

您可以尝试:

StringBuilder sb = new StringBuilder(); 

string[] columnNames = dt.Columns.Cast<DataColumn>().
                              Select(column => column.ColumnName).
                              ToArray();
sb.AppendLine(string.Join("|", columnNames));

foreach (DataRow row in dt.Rows)
{
    string[] fields = row.ItemArray.Select(field => field.ToString()).
                                ToArray();
    sb.AppendLine(string.Join("|", fields));
}

File.WriteAllText("test.csv", sb.ToString());

答案 1 :(得分:1)

我以前使用此solution

我输出了200k记录,花了大约20秒。

答案 2 :(得分:0)

试试这个

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

using System.IO;

namespace ConsoleApplication33
{
    class Program
    {
        const stating FILENAME = @"c:\temp\test.txt";
        static void Main(string[] args)
        {
            DataTable dtFile1 = new DataTable();
            StreamWriter writer = new StreamWriter(FILENAME);

            foreach (DataRow row in dtFile1.AsEnumerable())
            {
                writer.WriteLine(string.Join("|", row.ItemArray.Select(x => x.ToString())) + "|");
            }

        }

    }
}