GurdeepS
GurdeepS

Reputation: 67213

Exporting to CSV using Winforms (built in)

Is there a way to implement csv exporting from a datagrid, using .NET 2.0 Winforms?

Thanks

Upvotes: 2

Views: 2481

Answers (1)

ChrisF
ChrisF

Reputation: 137138

There's nothing built in, but it's fairly straightforward to do yourself.

// Create the CSV file to which grid data will be exported.
StreamWriter sw = new StreamWriter("~/GridData.txt", false);

DataTable dt = GetDataTable(); // Pseudo code

// First we will write the headers.
sw.WriteLine(string.Join(",", dt.Columns.Select(c => c.ColumnName)));

// Now write all the rows.
int iColCount = dt.Columns.Count;
foreach (DataRow dr in dt.Rows)
{
    List<string> columnData = new List<string>();
    for (int i = 0; i < iColCount; i++)
    {
        if (!Convert.IsDBNull(dr[i]))
        {
            columnData.Add(dr[i].ToString());
        }
        else
        {
            columnData.Add(string.Empty);
        }
    }
    sw.WriteLine(string.Join(",", columnData.ToArray()));
}

sw.Close();

There are certainly further optimisations and improvements that can be made to this code. I'm not happy with the code that writes out the rows.

Upvotes: 2

Related Questions