ybt
asked on
C# Export DataGridView
Could anybody help how to export DataGridView to a tab delimited text file in C#?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
You can also surely cast the the DataSource property of the grid into a datatable and use this trick: http://emoreau.com/Entries/Articles/2009/04/Using-LINQ-and-XML-Literals-to-transform-a-DataTable-into-a-HTML-table.aspx
Try this:
var sb = new StringBuilder();
var headers = dataGridView1.Columns.Cast<DataGridViewColumn>();
sb.AppendLine(string.Join(",", headers.Select(column => "\"" + column.HeaderText + "\"").ToArray()));
foreach (DataGridViewRow row in dataGridView1.Rows)
{
var cells = row.Cells.Cast<DataGridViewCell>();
sb.AppendLine(string.Join(",", cells.Select(cell => "\"" + cell.Value + "\"").ToArray()));
}
System.IO.StreamWriter file = new System.IO.StreamWriter(@"\YourFile.csv");
file.WriteLine(sb.ToString());
ASKER
Thank you, it works, others advises is fine, but about coma separated and my particular need was tab delimited file.