导出到excel返回空白excel电子表格

时间:2016-06-21 19:41:59

标签: c# asp.net excel export

我有以下代码将GridView导出到excel文件中。从理论上讲,这段代码应该没有任何麻烦导出。但是,它正在导出空白。

public static void Export(string fileName, GridView gv, System.Web.UI.Control parentControl)
    {
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename=" + fileName + ".xls"));
        HttpContext.Current.Response.ContentType = "application/ms-excel";

        using (StringWriter sw = new StringWriter())
        {
            using (HtmlTextWriter htw = new HtmlTextWriter(sw))
            {
                //  Create a table to contain the grid
                Table table = new Table();

                //  include the gridline settings
                table.GridLines = gv.GridLines;

                //  add the header row to the table
                if (gv.HeaderRow != null)
                {
                    GridViewExportUtil.PrepareControlForExport(gv.HeaderRow);
                    table.Rows.Add(gv.HeaderRow);
                }

                //  add each of the data rows to the table
                foreach (GridViewRow row in gv.Rows)
                {
                    GridViewExportUtil.PrepareControlForExport(row);
                    table.Rows.Add(row);
                }

                //  add the footer row to the table
                if (gv.FooterRow != null)
                {
                    GridViewExportUtil.PrepareControlForExport(gv.FooterRow);
                    table.Rows.Add(gv.FooterRow);
                }

                //Control 'Content_ctlDisplayIssues_gvIssues' of type 'GridView' must be placed inside a form tag with runat=server.
                System.Web.UI.HtmlControls.HtmlForm form = new System.Web.UI.HtmlControls.HtmlForm();
                parentControl.Controls.Add(form);
                form.Controls.Add(gv);
                form.RenderControl(htw);

                //  render the htmlwriter into the response
                HttpContext.Current.Response.Write(sw.ToString());
                HttpContext.Current.Response.End();
            }
        }
    }

    /// <summary>
    /// Replace any of the contained controls with literals
    /// </summary>
    /// <param name="control"></param>
    private static void PrepareControlForExport(Control control)
    {
        for (int i = 0; i < control.Controls.Count; i++)
        {
            Control current = control.Controls[i];
            if (current is LinkButton)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text));
            }
            else if (current is ImageButton)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText));
            }
            else if (current is HyperLink)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text));
            }
            else if (current is DropDownList)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text));
            }
            else if (current is CheckBox)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False"));
            }
            else if (current is Image)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as Image).AlternateText));
            }

            if (current.HasControls())
            {
                GridViewExportUtil.PrepareControlForExport(current);
            }
        }
    }
}

我在这里遗漏了什么吗?

2 个答案:

答案 0 :(得分:0)

您是否曾在NotePad中打开过Excel文件?它里面没有HTML!然而,您正在使用HtmlTextWriter将数据流式传输到浏览器。我认为这不会起作用。

如果您真的决定将数据转换为Excel原生格式,可以使用Excel interop,也可以寻找更精简的第三方转换工具。

如果您只是需要用户在Excel中打开电子表格,但您并不关心如何将数据传输到浏览器,我建议您使用CSV格式的数据流式传输数据。 this article

答案 1 :(得分:0)

大部分代码都是正确的。这里的问题是HTML Writer没有正确呈现。 John Wu在他的回答中提到了这一点。所以这里的走动很简单:

而不是;

//Control 'Content_ctlDisplayIssues_gvIssues' of type 'GridView' must be placed inside a form tag with runat=server.
System.Web.UI.HtmlControls.HtmlForm form = new System.Web.UI.HtmlControls.HtmlForm();
parentControl.Controls.Add(form);
form.Controls.Add(gv);
form.RenderControl(htw);
我用过;

//here the table is rendered into the html writer
table.RenderControl(htw);

也很重要,就是在Web.config文件中添加此代码

<add key="PageInspector:ServerCodeMappingSupport" value="Disabled" />

这对我无缝起作用。