已将gridview转换为csv,但没有标头

本文关键字:gridview 转换 csv 已将 | 更新日期: 2023-09-27 17:59:09

我将gridview转换为CSV,但gridview上的标题没有显示在CSV文件中。

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();
}

已将gridview转换为csv,但没有标头

在读取单元格之前,请读取行标题的值。

PS:第一个附加";"用于行标题的列标题。

    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);
    }