以下代码适用于我并保留所有表格格式。源html表需要具有属性runat =“Server”,并且显然可以使用id。
基本上,它创建了一个新的(虚拟)表单,它只包含你的表并将其写入excel文件。如果您使用的是Excel 2007,您将收到一条令人恼火的错误消息:“您尝试打开的文件格式与扩展程序指定的格式不同”,但您可以放心地忽略它,并说“是”,您想要打开它
Public Sub exportTableExcel(ByVal aTable, ByVal filename)
Dim sw As New StringWriter()
Dim htw As New HtmlTextWriter(sw)
HttpContext.Current.Response.ClearContent()
HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=" & filename)
HttpContext.Current.Response.ContentType = "application/vnd.xls"
HttpContext.Current.Response.Charset = ""
' Create a form to contain the table
Dim frm As New HtmlForm()
aTable.Parent.Controls.Add(frm)
frm.Attributes("runat") = "server"
'prevent additional code from being exported
frm.attributes("maintainScrollPositionOnPostBack") = "false"
frm.Controls.Add(aTable)
frm.RenderControl(htw)
HttpContext.Current.Response.Write(sw.ToString())
HttpContext.Current.Response.End()
frm.Dispose()
htw.Dispose()
sw.Dispose()
End Sub