HTTP标头发送异常后,服务器无法设置内容类型

时间:2016-04-13 14:54:03

标签: c# asp.net export-to-excel

我收到"Server cannot set content type after HTTP headers have been sent "以下代码导出到excel的异常

private void ExportToExcel()
    {
        try
        {
            DateTime date = new DateTime();

            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.ClearContent();

            HttpContext.Current.Response.ClearHeaders();
            HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName + ".xls");
            HttpContext.Current.Response.ContentType = "application/ms-excel";
            HttpContext.Current.Response.BufferOutput = true;
            HttpContext.Current.Response.Write(@"<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.0 Transitional//EN"">");

            HttpContext.Current.Response.Charset = "utf-8";

            //Check the current culture;if its polish / Czech set the windows code to 1250 else set the windows code to 1252

            if (CultureInfo.CurrentCulture.ThreeLetterISOLanguageName.ToUpper(CultureInfo.CurrentCulture) == "CES" || CultureInfo.CurrentCulture.ThreeLetterISOLanguageName.ToUpper(CultureInfo.CurrentCulture) == "POL")
                HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("windows-1250");
            else
                HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("windows-1252");

            HttpContext.Current.Response.Write("<font style='font-size:10.0pt; font-family:Calibri;'>");
            HttpContext.Current.Response.Write("<BR><BR><BR>");
            HttpContext.Current.Response.Write("<Table border='1' bgColor='#ffffff' " +
              "borderColor='#000000' cellSpacing='0' cellPadding='0' " +
              "style='font-size:10.0pt; font-family:Calibri; background:white;'> <TR>");

            for (int j = 0; j < gridView.Columns.Count; j++)
            {
                HttpContext.Current.Response.Write("<Td>");
                HttpContext.Current.Response.Write("<B>");
                HttpContext.Current.Response.Write(gridView.Columns[j].HeaderText.ToString());
                HttpContext.Current.Response.Write("</B>");
                HttpContext.Current.Response.Write("</Td>");
            }
            HttpContext.Current.Response.Write("</TR>");
            foreach (DataRow row in orderDetails.Rows)
            {
                //format DateTime to show only Date
                if (isDeliveries && row[4].ToString() != null)
                    date = (DateTime)row[4];
                else if (row[5].ToString() != null)
                    date = (DateTime)row[5];

                HttpContext.Current.Response.Write("<TR>");
                for (int i = 0; i < orderDetails.Columns.Count; i++)
                {
                    if (i < columnsOrder.Length)
                    {
                        if (i == 4)
                        {
                            HttpContext.Current.Response.Write("<Td>");
                            HttpContext.Current.Response.Write(date.ToString("d"));
                            HttpContext.Current.Response.Write("</Td>");
                        }
                        else
                        {
                            HttpContext.Current.Response.Write("<Td>");
                            HttpContext.Current.Response.Write(row[columnsOrder[i]].ToString());
                            HttpContext.Current.Response.Write("</Td>");
                        }
                    }
                }
                HttpContext.Current.Response.Write("</TR>");
            }

            HttpContext.Current.Response.Write("</Table>");
            HttpContext.Current.Response.Write("</font>");
            HttpContext.Current.Response.Flush();

            HttpContext.Current.Response.SuppressContent = true;
            HttpContext.Current.ApplicationInstance.CompleteRequest();
        }
        catch (Exception ex)
        {
        }
    }

堆栈跟踪

   at System.Web.HttpResponse.set_ContentType(String value)
   at System.Web.HttpResponseInternalWrapper.set_ContentType(String value)
   at System.Web.UI.PageRequestManager.RenderPageCallback(HtmlTextWriter writer, Control pageControl)
   at System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children)
   at System.Web.UI.Control.RenderChildren(HtmlTextWriter writer)
   at System.Web.UI.Page.Render(HtmlTextWriter writer)
   at System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter)
   at System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter)
   at System.Web.UI.Control.RenderControl(HtmlTextWriter writer)
   at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)

即使经过大量的解决方法,我也无法修复它。有人可以帮助。

1 个答案:

答案 0 :(得分:0)

以下代码块实际上是设置Content-Encoding HTTP标头

if (CultureInfo.CurrentCulture.ThreeLetterISOLanguageName.ToUpper(CultureInfo.CurrentCulture) == "CES" || CultureInfo.CurrentCulture.ThreeLetterISOLanguageName.ToUpper(CultureInfo.CurrentCulture) == "POL")
    HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("windows-1250");
else
    HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("windows-1252");

因此,在将任何内容写入响应流之前必须先调用它,即HttpContext.Current.Response.Write(@"<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.0 Transitional//EN"">");