0

I converted gridview to CSV but the headers on the gridview are not shown on the CSV file.

public void btnToCSV_Click(object sender, EventArgs e)
{
    Response.Clear();
    Response.Buffer = true;
    Response.AddHeader("content-disposition", "attachment;filename=Report.csv");
    Response.Charset = "";
    Response.ContentType = "application/text";
    gvReport.AllowPaging = false;
    StringBuilder sBuilder = new System.Text.StringBuilder();
    for(int index = 0; index < gvReport.Columns.Count; index++)
    {
        sBuilder.Append(gvReport.Columns[index].HeaderText + ',');
    }
    sBuilder.Append("\r\n");
    for(int i = 0; i <gvReport.Rows.Count; i++)
    {
        for(int k = 0; k < gvReport.HeaderRow.Cells.Count; k++)
        {
            sBuilder.Append(gvReport.Rows[i].Cells[k].Text.Replace(",","") + ",");
        }
        sBuilder.Append("\r\n");
    }
    Response.Output.Write(sBuilder.ToString());
    Response.Flush();
    Response.End();
}
HasaniH
  • 8,232
  • 6
  • 41
  • 59
  • What do you see on the top line of the resulting CSV? Is it just commas? – Jimmy Smith Jul 28 '16 at 16:09
  • You've got a number of issues. You're taking a UI control and exporting that. Instead, you should export the underlying data directly. You're rolling your own CSV generator instead of using something purpose-built to handle all the nuances. And you're [using the wrong MIME type](http://stackoverflow.com/questions/7076042/what-mime-type-should-i-use-for-csv). – mason Jul 28 '16 at 16:38
  • @JimmySmith I see blank spaces in the top line – Abhi Jul 28 '16 at 17:01

1 Answers1

0

Before reading the cells read the value of the row header.

PS: The first append " ; " is for the column header of the row header.

    var sBuilder = new StringBuilder();
    sBuilder.Append(";");
    // ColumnsHeader
    foreach (DataGridViewColumn column in gvReport.Columns)
    {
        sBuilder.Append(String.Concat(column.HeaderText, ";"));
    }
    foreach (DataGridViewRow row in gvReport.Rows)
    {
        // RowHeader
        sBuilder.Append(String.Concat(row.HeaderCell.Value, ";"));

        // Cells
        foreach (DataGridViewCell cell in row.Cells)
        {
            sBuilder.Append(String.Concat(cell.Value, ";"));
        }
        sBuilder.Append(Environment.NewLine);
    }