简体   繁体   中英

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.

You need to change the ContentType .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM