Search code examples
c#excelexportexport-to-excelstringbuilder

Excel not opening .xls made from C# StringBuilder


The following code was written several months ago and tested perfectly, with that funny little warning message in Excel. Now, though, after the C# code runs without errors and the browser downloads the exported .xls file, the Excel application opens but displays nothing, as if it didn't open the exported file. Can anyone see problems with this code or know why Excel suddenly wouldn't open this document? Many thanks in advance!

The C# Code:

[HttpGet]
public void DownloadReport()
{
    string filename = "ReportExport";

    //Report source data organized here

    StringBuilder sb = new StringBuilder();
    sb.Append("<table>");
    sb.Append("<tr>");
    foreach (DataColumn column in reportData.Columns)
    {
        sb.Append("<th>");
        sb.Append(column.ColumnName);
        sb.Append("</th>");
    }
    sb.Append("</tr>");
    foreach (DataRow row in reportData.Rows)
    {
        sb.Append("<tr>");
        foreach (DataColumn column in reportData.Columns)
        {
            sb.Append("<td>");
            if (row[column] == null)
            {
                sb.Append("");
            }
            else
            {
                sb.Append(row[column]);
            }
            sb.Append("</td>");
        }
        sb.Append("</tr>");
    }
    sb.Append("</table>");
    Response.Clear();
    Response.Buffer = true;
    Response.AddHeader("content-disposition", "attachment;filename=" + fileName + ".xls");
    Response.Charset = "";
    Response.ContentType = "application/vnd.ms-excel";
    string style = @"<style> .textmode { } </style>";
    Response.Write(style);
    Response.Output.Write(sb.ToString());
    Response.Flush();
    Response.End();
}

Solution

  • Adding Response.ClearHeaders() before setting the header seems to have done the trick. Perhaps the content type had been previously specified and needed to be reset.