Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/318.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从ASP.NET打开导出的Excel工作表时,格式或扩展名无效_C#_Asp.net - Fatal编程技术网

C# 从ASP.NET打开导出的Excel工作表时,格式或扩展名无效

C# 从ASP.NET打开导出的Excel工作表时,格式或扩展名无效,c#,asp.net,C#,Asp.net,我正在尝试使用Response将HTML从我的ASP.NET应用程序导出到excel文件,按照此解决方案: 这正是我在单击“导出”按钮时导出HTML表的函数: protected void exportBtn_Click(object sender, EventArgs e) { string filename = "Results_" + DateTime.Now.ToString("ddMMyyyy")+".xlsx"; R

我正在尝试使用
Response
将HTML从我的ASP.NET应用程序导出到excel文件,按照此解决方案:

这正是我在单击“导出”按钮时导出HTML表的函数:

protected void exportBtn_Click(object sender, EventArgs e)
        {

            string filename = "Results_" + DateTime.Now.ToString("ddMMyyyy")+".xlsx";
            Response.Clear();
            Response.ContentType = "application/x-msexcel";
            Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", filename));
            Response.ContentEncoding = Encoding.UTF8;
            StringWriter stringWriter = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(stringWriter);
            resultTable.RenderControl(hw);
            Response.Write(stringWriter.ToString());
            Response.End();

        }
导出完成后,当我尝试打开生成的
.xlsx
文件时,它会显示以下消息:


你知道如何解决这个问题吗?

简单的解决方案是将
ContentType
“application/x-msexcel”
更改为
“application/vnd.ms excel”
,并使用
.xls
作为扩展,而不是使用
.xlsx

最终代码为:

protected void exportBtn_Click(object sender, EventArgs e)
        {

            string filename = "Results_" + DateTime.Now.ToString("ddMMyyyy")+".xls";
            Response.Clear();
            Response.ContentType = "application/vnd.ms-excel";
            Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", filename));
            Response.ContentEncoding = Encoding.UTF8;
            StringWriter stringWriter = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(stringWriter);
            resultTable.RenderControl(hw);
            Response.Write(stringWriter.ToString());
            Response.End();

        }

开始使用专门的库来创建Excel文件,例如。您现在所做的就是创建一个扩展名为.xls的HTML页面。@VDWWD但它以前是可以工作的,我不知道这有什么问题。它以前是否可以工作并不重要。它不应该工作。为什么要使用XLS?它不是Excel文件。@mason idk它可以工作,我搜索了这个扩展名,发现它是Excel文件,是int吗?不是。简单地在文件上添加XLS扩展名并不能使它成为Excel文件。它使它成为伪装成Excel文件的HTML文件。“这是一个肮脏的黑客行为。”梅森:我明白了,还有更好的建议吗?VDWWD已经在对这个问题的评论中涵盖了正确的解决方案。