[英]Export DataTable to CSV File with “|” Delimiter
I am building an ASP.NET C# project that has a functionality to export DataTables to CSV files with a |
我正在构建一个ASP.NET C#项目,该项目具有使用|
将DataTables导出到CSV文件的功能|
delimiter for each cell. 每个单元格的分隔符。 I want it to look like this: 我希望它看起来像这样:
100001|06/19/1861|Jose|Rizal|Filipino|Calamba, Laguna| 100002|08/30/1850|Marcelo|Del Pilar|Filipino|| 100003||||||
As you can see, each 'cell' is delimited by |
如您所见,每个“单元格”由|
分隔|
. 。 Furthermore, null cells should also have the delimiter. 此外,空单元格也应具有定界符。 All rows should have the same number of |
所有行应具有相同的|
号。 delimiter. 定界符。
So far I have this code: 到目前为止,我有以下代码:
StringBuilder sb = new StringBuilder();
DataTable dtFile1 = file1BLO.SelectAllFile1();
foreach (DataRow dr in dtFile1.Rows)
{
//build text file
}
You can try: 你可以试试:
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());
Try this 尝试这个
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())) + "|");
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.