导出的CSV文件为空

本文关键字:文件 CSV | 更新日期: 2023-09-27 18:22:22

我有这段代码,可以将数据从GridView导出到csv。它可以与其他网站合作,但不适用于我目前正在开发的网站。

GridView在代码隐藏中与DataTable绑定。以下是将提取和数据绑定到GridView的事件。

    private void bindGridView()
    {
        //Fetching data from DB goes here
        myTable.Columns.Add("type", typeof(int));
        myTable.Columns.Add("rate", typeof(int));
        foreach (DataRow rows in myTable.Rows)
        {
            if (rows["dst"].ToString() == "1875")
            {
                rows["type"] = 1;
                rows["rate"] = 500;
                rows.AcceptChanges();
            }
            else if (rows["dst"].ToString() == "1876")
            {
                rows["type"] = 0;
                rows["rate"] = 30;
                rows.AcceptChanges();
            }
        }
        gridViewData.DataSource = myTable;
        gridViewData.AllowPaging = true;
        gridViewData.PageSize = 10;
        gridViewData.DataBind();
    }

以下是从GridView 导出数据的按钮点击事件

    protected void btnExportCDR_Click(object sender, EventArgs e)
    {
        if (gridViewData.Rows.Count == 0)
        {
            lblStatus.Text = "Data is empty. Can not export CDR. Please check your filtering dates.";
        }
        else
        {
            Response.Clear();
            Response.Buffer = true;
            Response.AddHeader("content-disposition", "attachment;filename=CDRMMCC_" + System.DateTime.Now.ToShortDateString() + ".csv");
            Response.Charset = "";
            Response.ContentType = "application/text";

            bindGridView();
            gridViewData.AllowPaging = false;

            StringBuilder sb = new StringBuilder();
            //I did a trace here, gridViewData.Columns.Count is 0. That's why it got skipped, I think.
            for (int k = 0; k < gridViewData.Columns.Count; k++)
            {
                sb.Append(gridViewData.Columns[k].HeaderText + ",");
            }
            sb.Append("'r'n");
            for (int i = 0; i < gridViewData.Rows.Count; i++)
            {
                for (int k = 0; k < gridViewData.Columns.Count; k++)
                {
                    sb.Append(gridViewData.Rows[i].Cells[k].Text + ",");
                }
                sb.Append("'r'n");
            }
            Response.Output.Write(sb.ToString());
            Response.Flush();
            Response.End();
        }
    }

请提供建议。

导出的CSV文件为空

如果使用设置为trueGridViewAutoGenerateColumns属性,则Columns集合将为空。此属性的MSDN文档中写道:

"自动生成的绑定列字段不会添加到Columns集合中"

这就是Columns集合为空的原因。正如Henk Holterman所指出的,直接使用DataTable来生成CSV文件。

另一种方法是将AutoGenerateColumns属性设置为false并显式定义列。

除了Hans-answer,您还可以使用GridView的RenderControl,这减少了您的工作量。

StringWriter strWriter = new StringWriter();
HtmlTextWriter htmlWriter = new HtmlTextWriter(strWriter);
MyGridView.RenderControl(htmlWriter);
Response.Write(strWriter.ToString());