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

时间:2017-05-30 12:49:40

标签: c# excel export-to-excel

以下是用于导出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();
    }

代码工作并导出报告,但是当我在“ms excel”中修改Excel工作表并尝试保存它保存为网页格式的文件时。 我希望默认格式为Excel。

提前致谢。

1 个答案:

答案 0 :(得分:1)

您需要更改ContentType

对于.xls个文件,它是"application/vnd.ms-excel"