1

I have a DataSet. I would like to 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

Roseele Dahang
  • 101
  • 1
  • 1
  • 8

3 Answers3

5
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);
Alex Aza
  • 76,499
  • 26
  • 155
  • 134
4

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"); 
}
Jason Jong
  • 4,310
  • 2
  • 25
  • 33
  • @Alex, I edited the original code, which was comma separated and converted it to tab separated now. Right now it doesnt include header. Quite easy to get that.. I'll edit it now – Jason Jong Jun 07 '11 at 02:33
  • Also, there will be redundant trailing tab. – Alex Aza Jun 07 '11 at 02:34
  • @Alex, quite easy to remove the trailing tab if the OP wanted to, but in this context where each data is wrapped in quote marks, the trailing tab would be ignored by the CSV reader – Jason Jong Jun 07 '11 at 02:40
0

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

using System.Linq;
Horizon_Net
  • 5,959
  • 4
  • 31
  • 34
Robbie
  • 61
  • 6