【问题标题】:converted gridview to csv but no headers将gridview转换为csv但没有标题
【发布时间】:2016-12-03 03:31:45
【问题描述】:

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

【问题讨论】:

  • 您在生成的 CSV 的第一行看到了什么?只是逗号吗?
  • 你有很多问题。您正在使用 UI 控件并将其导出。相反,您应该直接导出基础数据。您正在使用自己的 CSV 生成器,而不是使用专门构建的东西来处理所有细微差别。你是using the wrong MIME type
  • @JimmySmith 我看到顶行有空格

标签: c# asp.net gridview export-to-csv


【解决方案1】:

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

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

【讨论】:

  • 谢谢,但 DataGridViewColumn 不能在我的代码中使用。是否需要添加额外的命名空间?
  • 试试这个,在那一行,foreach (GridViewColumn column in gvReport.HeaderRow)
  • 仍然没有帮助@JimmySmith
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-29
  • 1970-01-01
  • 2018-12-27
  • 1970-01-01
  • 1970-01-01
  • 2016-06-29
相关资源
最近更新 更多