Manishmz
Manishmz

Reputation: 9

C#: Try to save Exported excel file but it save as Web Page(.html)

Below is my code used to export the excel file.

public void ExportReport()
    {
        DataTable dataTable = new DataTable();
        dataTable = getDataTable();
        HttpResponse response = HttpContext.Current.Response;
        GridView grdExportData = new GridView();

        grdExportData.AllowPaging = false;
        grdExportData.DataSource = dataTable;
        grdExportData.DataBind();

        //Clear the response and add the content types and headers to it.
        response.Clear();
        response.ClearContent();
        response.ContentType = "application/octet-stream";
        DateTime currDate = DateTime.Now;
        response.AddHeader("Content-Disposition", "attachment; filename=report.xls")

        // Create a dynamic control, populate and render it
        GridView excel = new GridView();
        excel.DataSource = dataTable;
        excel.DataBind();
        HtmlTextWriter htmlTextWriter = new HtmlTextWriter(response.Output);
        htmlTextWriter.Write("<table><tr><td colspan='3'><b>Report Title</b></td><td colspan='1'></td><td colspan='1'><b>Date: &nbsp;</b></td><td colspan='1'>" + DateTime.Today.ToString("MM/dd/yyyy") + "</td></tr></table>");
        excel.RenderControl(htmlTextWriter);
        response.Flush();
        response.End();
    }

Code works and exported the report but when I modify the excel sheet in "ms excel" and try to save the file it saved as web page format. I want default format as Excel.

Thanks in advance.

Upvotes: 0

Views: 1171

Answers (1)

g0np
g0np

Reputation: 309

You need to change the ContentType.

For .xls files it is "application/vnd.ms-excel"

Upvotes: 1

Related Questions