如何将数据从gridview导出到excel2003,2007,2010,没有警告信息

我想从gridview导出数据为Excel。 我有我的电脑上安装的Office 2010。 当我试图打开excel文件,它给了我错误,即“你试图打开的文件是在不同的格式比指定的文件扩展名c#”。

我的代码导出gridview:

Protected Sub btnexptoexcel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnexptoexcel.Click Try Response.Clear() Response.Buffer = True Response.AddHeader("content-disposition", "attachment;filename=Complaint_Details.xls") Response.Charset = "" Response.ContentType = "application/ms-excel" Using sw As New StringWriter() Dim hw As New HtmlTextWriter(sw) grd_ComplaintDetails.AllowPaging = False grd_ComplaintDetails.HeaderRow.BackColor = Color.White For Each cell As TableCell In grd_ComplaintDetails.HeaderRow.Cells cell.BackColor = grd_ComplaintDetails.HeaderStyle.BackColor Next For Each row As GridViewRow In grd_ComplaintDetails.Rows row.BackColor = Color.White For Each cell As TableCell In row.Cells If row.RowIndex Mod 2 = 0 Then cell.BackColor = grd_ComplaintDetails.AlternatingRowStyle.BackColor Else cell.BackColor = grd_ComplaintDetails.RowStyle.BackColor End If cell.CssClass = "textmode" Next Next grd_ComplaintDetails.RenderControl(hw) Dim style As String = "<style> .textmode { } </style>" Response.Write(style) Response.Output.Write(sw.ToString()) Response.Flush() Response.[End]() End Using Catch ex As Exception div_Msg.InnerText = "Can not generate Excel File" End Try End Sub 

我的问题是,当我打开文件(在MSOffice 2003,2007或2010),它不应该给我的文件扩展名的错误…你能告诉我什么是我应该在代码中作出的更改?

微软的文章说Excel使用以下扩展:

  • .xls – 是Excel 97 – Excel 2003二进制文件格式(BIFF8)。
  • .xlsx – 默认的Office Excel 2007基于XML的文件格式。 不能存储Microsoft Visual Basic for Applications(VBA)macros代码或Microsoft Office Excel 4.0macros表(.xlm)。
  • .xlt – Excel模板的Excel 97 – Excel 2003二进制文件格式(BIFF8)。
  • .xlsm基于Office Excel 2007 XML和启用macros的文件格式。 存储VBAmacros代码或Excel 4.0macros表(.xlm)。
  • .xltx Excel模板的默认Office Excel 2007文件格式。 无法存储VBAmacros代码或Excel 4.0macros表(.xlm)。
  • .xla Excel 97-2003加载项,旨在运行其他代码的补充程序。 支持使用VBA项目。

您的偏好是MSOffice 2003,2007或2010

所以你必须select

Response.AddHeader("content-disposition", "attachment;filename=Complaint_Details.xlsx")代替Complaint_Details.xls"

如果你可以做到这一点,请尝试将文件保存为.xlsxexcel 2007+

 Response.AddHeader("content-disposition", "attachment;filename=Complaint_Details.xlsx") 

另外,我build议尝试这个免费的库来处理xlsx Excel文件。 EPPLUS非常好。 epplus.codeplex.com

如果您需要专门的xls文件( excel 2003及更早版本),则不支持EPPLUS,但您可以使用其他库NPOI https://npoi.codeplex.com/来支持它&#x4EEC;

我一直有同样的问题。 我终于用记事本打开了RenderControl输出的内容,发现它实际上是一个网页,不pipe扩展名是什么。 这就是为什么你会收到警告信息。 用户实际上必须从Excel保存为Excel文件。

另一个缺点是网格中的内容也会呈现所有的代码。 所以,列标题将链接回doPostBack函数和超链接将仍然具有无效的引用。

我已经看过这个方法很多次了,但这不是一个完美的解决scheme。