开发者

Convert Dataset to Textfile tab delimited file

开发者 https://www.devze.com 2023-03-11 22:27 出处:网络
I have a DataSet. I would like t开发者_开发知识库o convert dataset column as header and row data as data into a tab delimited text file.

I have a DataSet. I would like t开发者_开发知识库o convert dataset column as header and row data as data into a tab delimited text file.

Is there any technique I can do in my end or I have to do the looping manually?

Sincerely Thanks, - Sel


private static string GetTextFromDataTable(DataTable dataTable)
{
    var stringBuilder = new StringBuilder();
    stringBuilder.AppendLine(string.Join("\t", dataTable.Columns.Cast<DataColumn>().Select(arg => arg.ColumnName)));
    foreach (DataRow dataRow in dataTable.Rows)
        stringBuilder.AppendLine(string.Join("\t", dataRow.ItemArray.Select(arg => arg.ToString())));
    return stringBuilder.ToString();
}

Usage:

var text = GetTextFromDataTable(dataSet.Tables[0]);
File.WriteAllText(filePath, text);


Exporting to XML is built right in, but exporting to CSV, you can use the following code - from http://social.msdn.microsoft.com/Forums/en-US/vbgeneral/thread/d2071fd4-8c7d-4d0e-94c3-9586df754df8/

this only writes the data, not the columns, you'll need to loop the column headers first..

Edit: Updated to include column names... I have not run this, and this is an edit from the link above, so it may or may not work, but the concept is here

StringBuilder str = new StringBuilder(); 
    // get the column headers
foreach (var c in NorthwindDataSet.Customers.Columns) { 
  str.Append("\"" + c.ColumnName.ToString() + "\"\t"); 
} 
str.Append("\r\n");

    // write the data here
foreach (DataRow dr in this.NorthwindDataSet.Customers) { 
 foreach (var field in dr.ItemArray) { 
   str.Append("\"" + field.ToString() + "\"\t"); 
 } 
 str.Append("\r\n");
} 
try { 
 My.Computer.FileSystem.WriteAllText("C:\\temp\\testcsv.csv", str.ToString(), false); 
} catch (Exception ex) { 
 MessageBox.Show("Write Error"); 
}


Note you will need to be using Linq for this solution to work. Add the following using statement to your code:

using System.Linq;
0

精彩评论

暂无评论...
验证码 换一张
取 消