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

时间:2012-12-06 05:28:32

标签: c# asp.net gridview export-to-excel

我尝试了网站中提到的一些解决方案,例如Using System.Microsoft.Office.ExcelExcel = 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();
 }

因此,当用户打开下载的文件时,会发出警告,因为它不在同一个扩展名中。 为什么会这样?.. ??

我尝试使用各种网站提供的解决方案,但无济于事......

由于

2 个答案:

答案 0 :(得分:0)

尝试使用

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

答案 1 :(得分:0)

尝试将Response.ContentType = "application/vnd.xls";更改为Response.ContentType = "application/vnd.ms-excel"

另外

Microsoft文档说:

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

也可访问此网站:http://devblog.grinn.net/2008/06/file-you-are-trying-to-open-is-in.html

相关问题