我想在 VB.Net 中使用数据库查询生成一个 Excel 文件。我该怎么做?
更准确地说:我想将查询“绑定(bind)”(很像将查询绑定(bind)到 GridView)到 Excel 文件,这样表中的行将占据新 Excel 文件中的相应单元格,并保存文件到我的电脑。然后,将该文件邮寄给某人。
虽然我可以处理邮寄部分,但我需要帮助才能创建此类文件。任何人都知道如何实现我想要实现的目标?
PS:我需要在 VB.Net 中执行此操作,并且我使用的是 SQL Server 2008。
最佳答案
好吧,这并不完美,但它应该可以帮助您入门。首先,您需要添加对您正在使用的 Excel 版本的引用。在我的例子中,它是 12.0 (2007),但这段代码应该可以与最后两个或三个版本一起使用,只需进行一两个较小的更改。在你的页面顶部添加这个
导入 Microsoft.Office.Interop
接下来添加创建数据表的函数
Public Function CreateTable() As DataTable
Dim cn As New SqlConnection(My.Settings.con)
Dim cmd As New SqlCommand
Using da As New SqlDataAdapter()
Dim dt As New DataTable()
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "[dbo].[MyStoredProcedure]"
cmd.CommandTimeout = 0
cn.Open()
cmd.Connection = cn
da.SelectCommand = cmd
da.Fill(dt)
cn.Close()
Return dt
End Using
End Function
接下来是获取该 DataTable 并将其转储到 Excel 中的代码。
Public Shared Sub PopulateSheet(ByVal dt As DataTable, ByVal File As String)
Dim oXL As Excel.Application = CType(CreateObject("Excel.Application"), Excel.Application)
Dim oWB As Excel.Workbook
Dim oSheet As Excel.Worksheet
Dim oRng As Excel.Range
oXL.Visible = True
oWB = oXL.Workbooks.Add
oSheet = CType(oWB.ActiveSheet, Excel.Worksheet)
Dim dc As DataColumn
Dim dr As DataRow
Dim colIndex As Integer = 0
Dim rowIndex As Integer = 0
For Each dc In dt.Columns
colIndex = colIndex + 1
oXL.Cells(1, colIndex) = dc.ColumnName
Next
For Each dr In dt.Rows
rowIndex = rowIndex + 1
colIndex = 0
For Each dc In dt.Columns
colIndex = colIndex + 1
oXL.Cells(rowIndex + 1, colIndex) = dr(dc.ColumnName)
Next
Next
oSheet.Cells.Select()
oSheet.Columns.AutoFit()
oSheet.Rows.AutoFit()
oXL.Visible = True
oXL.UserControl = True
oWB.SaveAs(File)
oRng = Nothing
oXL.Quit()
ExcelCleanUp(oXL, oWB, oSheet)
End Sub
现在您可以通过按钮或您选择的任何事件调用它
Dim dt As New DataTable
Try
dt = CreateTable()
PopulateSheet(dt, "c:\test\ExcelFile.xlsx")
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
dt.Dispose()
End Try
现在这是非常基本的,但只需稍加操作,您就可以进行单元格格式设置、页面设置以及几乎所有可以在 Excel 中使用菜单/选项完成的操作。
我们还应该通过添加代码来清理这些东西来完成它。
Private Shared Sub ExcelCleanUp( _
ByVal oXL As Excel.Application, _
ByVal oWB As Excel.Workbook, _
ByVal oSheet As Excel.Worksheet)
GC.Collect()
GC.WaitForPendingFinalizers()
Marshal.FinalReleaseComObject(oXL)
Marshal.FinalReleaseComObject(oSheet)
Marshal.FinalReleaseComObject(oWB)
oSheet = Nothing
oWB = Nothing
oXL = Nothing
End Sub
关于database - 如何在 VB.Net 中使用数据库查询创建 Excel 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5458890/