导出的CSV文件为空

时间:2012-02-04 09:43:06

标签: c# asp.net

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

GridView与代码隐藏的DataTable捆绑在一起。以下是绑定fetch并将数据绑定到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();
        }
    }

请建议。

2 个答案:

答案 0 :(得分:1)

如果您使用AutoGenerateColumns设置为GridView的{​​{1}}属性,true集合将为空。此属性的MSDN文档说:

“自动生成的绑定列字段未添加到列集合中”。

这是您的Columns集合为空的原因。正如Henk Holterman指出的那样,直接使用Columns生成CSV文件。

另一种方法是将DataTable属性设置为AutoGenerateColumns并明确定义列。

答案 1 :(得分:0)

除了Hans回答之外,您还可以使用GridView的RenderControl来减少您的工作。

StringWriter strWriter = new StringWriter();
HtmlTextWriter htmlWriter = new HtmlTextWriter(strWriter);

MyGridView.RenderControl(htmlWriter);
Response.Write(strWriter.ToString());