我在Asp.net有一个网站,我的代码如下
Protected Sub Button3_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button3.Click
Response.Clear()
Response.AddHeader("content-disposition", "attachment;filename=FileName.xls")
Response.Charset = ""
Response.ContentType = "application/vnd.xls"
Dim stringWrite As New System.IO.StringWriter()
Dim htmlWrite As System.Web.UI.HtmlTextWriter = New HtmlTextWriter(stringWrite)
GridView5.RenderControl(htmlWrite)
Response.Write(stringWrite.ToString())
Response.[End]()
End Sub
通过单击按钮下载文件,但是当我使用Microsoft Excel打开它时,它给我的消息是文件格式和扩展名不匹配有没有办法绕过它。我也尝试过使用像csv这样的替代格式。
答案 0 :(得分:0)
使用Imports ClosedXML.Excel
并添加以下代码可解决问题
aspx.vb
Protected Sub Button3_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button3.Click
Dim dt As New DataTable("GridView_Data")
For Each cell As TableCell In GridView5.HeaderRow.Cells
dt.Columns.Add(cell.Text)
Next
For Each row As GridViewRow In GridView5.Rows
dt.Rows.Add()
For i As Integer = 0 To row.Cells.Count - 1
dt.Rows(dt.Rows.Count - 1)(i) = row.Cells(i).Text
Next
Next
Dim wb As New XLWorkbook
wb.Worksheets.Add(dt)
Response.Clear()
Response.Buffer = True
Response.Charset = ""
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
Response.AddHeader("content-disposition", "attachment;filename=GridViewPOLQA.xlsx")
Using MyMemoryStream As New MemoryStream()
wb.SaveAs(MyMemoryStream)
MyMemoryStream.WriteTo(Response.OutputStream)
Response.Flush()
Response.[End]()
End Using
End Sub