简体   繁体   English

C#:尝试保存导出的excel文件,但将其另存为网页(.html)

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

Below is my code used to export the excel file. 下面是我用于导出excel文件的代码。

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. 代码可以正常工作并导出报告,但是当我在“ ms excel”中修改excel工作表并尝试将其保存为网页格式时保存文件。 I want default format as Excel. 我想要默认格式为Excel。

Thanks in advance. 提前致谢。

You need to change the ContentType . 您需要更改ContentType

For .xls files it is "application/vnd.ms-excel" 对于.xls文件,它是"application/vnd.ms-excel"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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