我想从gridview导出数据到excel。我的电脑上安装了office 2010。当我试图打开excel文件时,它给了我错误,即“您试图打开的文件的格式不同于文件扩展名c#指定的格式”。如何将数据从gridview导出到excel 2003,2007,2010没有警告信息
我对出口的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
我的问题是,当我打开文件(在2003的MSOffice,2007或2010),它不应该给我的文件扩展名错误... 你能告诉我什么是我应该在代码中做出的更改吗?
感谢您的回复...我根据您的评论替换我的代码,但它给了我错误,即“excel无法打开文件,因为文件格式无效。”..你能帮我吗? – 2014-09-03 13:04:35
@KishorRajendraKulkarni我不能,我不知道你在做什么......我建议用EPPLUS重写你的整个过程,然后根据提供的示例项目创建一个** valid **'xlsx'文件。 – Vland 2014-09-03 13:19:17