C# 将HTML表格导出到Excel时获取格式错误

C# 将HTML表格导出到Excel时获取格式错误,c#,excel,C#,Excel,我正在用c#将一个HTML表格导出到Excel,但打开Excel时会出现如下错误: 我尝试了一个不同的扩展名“officedocument.spreadsheetml.sheet”,比如.xlsx,但仍然出现同样的错误。下面是我的C#代码: //StrExport.Append(@“Time”); //StrExport.Append(@“”); StrExport.Append(@“Time”); StrExport.Append(@“”); StrExport.Append(“”); Ap

我正在用c#将一个HTML表格导出到Excel,但打开Excel时会出现如下错误:

我尝试了一个不同的扩展名“officedocument.spreadsheetml.sheet”,比如.xlsx,但仍然出现同样的错误。下面是我的C#代码:

//StrExport.Append(@“Time”);
//StrExport.Append(@“”);
StrExport.Append(@“Time”);
StrExport.Append(@“”);
StrExport.Append(“”);
Append(dvInfo.InnerHtml);
StrExport.Append(“”);
string strFile=“StudentInformations.xls”;
//字符串strFile=“StudentInformations.xlsx”;
字符串strcontentType=“应用程序/excel”;
//string strcontentType=“application/vnd.openxmlformats officedocument.spreadsheetml.sheet”;
Response.ClearContent();
Response.ClearHeaders();
Response.BufferOutput=true;
Response.ContentType=strcontentType;
AddHeader(“内容处置”、“附件;文件名=“+strFile”);
Write(StrExport.ToString());
Response.Flush();
Response.End();
请提供此消息的解决方案。

这是意料之中的。 您正在导出HTML,但将其命名为.xlsx。Excel足够聪明,可以解释它,但您将得到此警告


要没有警告,您需要使用现成的库以原生.xlsx格式生成输出。

我也设置了extension.xlsx,但当设置为xlsx时,excel不会打开。@jitendrakumar重要的是内容,而不是扩展名。将扩展名设置为PNG如何;它能神奇地将内容变成图像吗?@uwe Keim有什么解决方案吗???@jitendrakumar你读过答案了吗?您需要使用库以本机方式构建XLSX输出。您的代码只是呈现HTML并将其称为Excel文件。
//StrExport.Append(@"<html xmlns='urn:schemas-microsoft-com:office:Spreadsheet'  xmlns:ss='urn:schemas-microsoft-com:office:Spreadsheet'  xmlns='http://www.w3.org/TR/REC-html40'><head><title>Time</title>");
        //StrExport.Append(@"<body lang=EN-US id=h1><div class=Section1>");
        StrExport.Append(@"<html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:w='urn:schemas-microsoft-com:office:excel' xmlns='http://www.w3.org/TR/REC-html40'><head><title>Time</title>");
        StrExport.Append(@"<body lang=EN-US style='mso-element:header' id=h1><span style='mso--code:DATE'></span><div class=Section1>");
        StrExport.Append("<DIV  style='font-size:12px;'>");
        StrExport.Append(dvInfo.InnerHtml);
        StrExport.Append("</div></body></html>");
        string strFile = "StudentInformations.xls";
      //  string strFile = "StudentInformations.xlsx";
        string strcontentType = "application/excel";
        //string strcontentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        Response.ClearContent();
        Response.ClearHeaders();
        Response.BufferOutput = true;
        Response.ContentType = strcontentType;
        Response.AddHeader("Content-Disposition", "attachment; filename=" + strFile);
        Response.Write(StrExport.ToString());
        Response.Flush();            
        Response.End();