C# 从asp.net中的gridview导出到excel时出现格式错误

C# 从asp.net中的gridview导出到excel时出现格式错误,c#,asp.net,gridview,export-to-excel,C#,Asp.net,Gridview,Export To Excel,我尝试了一些网站上提到的解决方案,比如使用System.Microsoft.Office.Excel和Excel=System.Microsoft.Office.Excel,但都不管用。。。。 在这里,我试图获取表中的数据,并以.xls格式下载到服务器中指定位置的文件中,然后为用户提供下载该文件的链接。 这是出口代码` protected void btnExcelExport_Click(object sender, EventArgs e) { System.Text.StringB

我尝试了一些网站上提到的解决方案,比如使用System.Microsoft.Office.Excel和Excel=System.Microsoft.Office.Excel,但都不管用。。。。 在这里,我试图获取表中的数据,并以.xls格式下载到服务器中指定位置的文件中,然后为用户提供下载该文件的链接。 这是出口代码`

protected void btnExcelExport_Click(object sender, EventArgs e)
{
    System.Text.StringBuilder sb = new System.Text.StringBuilder();
    using (StringWriter sw = new StringWriter(sb))
    {
        using( HtmlTextWriter htw = new HtmlTextWriter(sw))
        {
            //  Create a form to contain the grid
            Table table = new Table();
            // get gridlines from gridview
            table.GridLines = GridView2.GridLines;
            if (GridView2.HeaderRow != null)
            {                       
                table.Rows.Add(GridView2.HeaderRow);
            }
            foreach (GridViewRow row in GridView2.Rows)
            {
                table.Rows.Add(row);
            }
            if (GridView2.FooterRow != null)
            {
                table.Rows.Add(GridView2.FooterRow);
            }    
            //  render the table into the htmlwriter
            table.RenderControl(htw);    
        }
        var myRootPath = Server.MapPath("~");
        var docPath = Path.GetFullPath(Path.Combine(myRootPath, "/Compare/c.xls")); 
        File.WriteAllText(docPath, sw.ToString());  
    }
    dwndlink.Visible = true;

}
当这是linkbutton的代码时:

 protected void dwnlink(object sender, EventArgs e)
 {   
     var webRootPath = Server.MapPath("~");
     var docPath = Path.GetFullPath(Path.Combine(webRootPath, "/Compare/c.xls"));

     string name = Path.GetFileName(docPath);
     Response.AppendHeader("content-disposition", "attachment; filename=" + name);
     Response.ContentType = "Application/vnd.ms-excel";
     Response.TransmitFile(docPath);
     Response.End();
 }
因此,当用户打开下载的文件时,会发出警告,因为它不在同一扩展名中。 为什么会这样

我尝试使用各种网站提供的解决方案,但都没有用

谢谢

尝试使用

Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"

尝试更改
Response.ContentType=“application/vnd.xls”
Response.ContentType=“application/vnd.ms excel”

微软的文件说:

“当前的设计不允许您在Excel中打开网站中的HTML内容……因此,返回HTML并将MIME类型设置为XLS之类的ASP页面试图强制HTML在Excel中打开,而不是在web浏览器中打开(如预期的那样)将始终收到安全警报…如果您使用HTML MIME类型,则web浏览器将打开内容而不是Excel。因此,对于这种情况没有很好的解决方法,因为HTML/MHTML缺少特定于Excel的特殊MIME类型。如果您同时控制web服务器和客户端桌面,则可以添加自己的MIME类型在需要访问时,最好的选择是使用不同的文件格式,或提醒用户警告,并告诉他们选择“是”对话框。“


也请访问此网站:

尝试了vid VN和ms excel…但是问题…(编辑:这个问题没有可行的解决方法,我的意思是我用完了msdn中提供的所有MIME类型…但是,问题还没有消失…谢谢