我有一个带有导出按钮的网页。按下此按钮时是否可以将sql表导出到excel?我可以用 gridview 来完成,但只想要一个简单的按钮,后面有代码来完成这项工作。有人可以指出我需要的方向吗?
问问题
1316 次
2 回答
3
这是您可以使用的实用程序功能:
Public Shared Sub ExportToSpreadsheet(table As DataTable, filename As String)
' Get a hold of the HTTP context and clear it, because we are going to push the CSV data through the context
Dim context = HttpContext.Current
context.Response.Clear()
' Loop through each column in your data table
For Each column As DataColumn In table.Columns
' Write column names
context.Response.Write(column.ColumnName + ";")
Next
context.Response.Write(Environment.NewLine)
' Loop through each row in the data table
For Each row As DataRow In table.Rows
' Loop through each column in row
For i As Integer = 0 To table.Columns.Count - 1
' Write each column value
context.Response.Write(row(i).ToString().Replace(";", [String].Empty) & ";")
Next
' Write a new line between rows of data
context.Response.Write(Environment.NewLine)
Next
' Set the content type and headers
context.Response.ContentType = "text/csv"
context.Response.AppendHeader("Content-Disposition", "attachment; filename=" & filename & ".csv")
context.Response.[End]()
End Sub
然后你可以这样称呼它:
ExportToSpreadsheet(YourDataTable, "YourFileName")
注意:既然是Shared
函数,那么你可以把它放在一个实用程序类中,不需要实例化(New
)类来使用函数。
于 2013-08-20T17:37:47.127 回答
1
如果你想要它在 excel 中,你可以使用下面的代码。选择数据并将其放入 Gridview 并执行以下操作。
Dim GridView1 As New GridView
SqlDataSource1.SelectCommand = "SELECT * FROM TableName"
GridView1.DataSource = SqlDataSource1
GridView1.DataBind()
Response.Clear()
Response.Buffer = True
Response.ContentType = "application/vnd.ms-excel"
Response.Charset = ""
Me.EnableViewState = False
Dim oStringWriter As New System.IO.StringWriter
Dim oHtmlTextWriter As New System.Web.UI.HtmlTextWriter(oStringWriter)
GridView1.RenderControl(oHtmlTextWriter)
Response.Write(oStringWriter.ToString())
Response.End()
您还可以格式化 Gridview 以使其在 Excel 工作表上看起来不错。
于 2013-08-20T17:57:06.717 回答