我想在VB.Net中使用数据库查询生成Excel文件.我该怎么做? 更确切地说:我想将查询“绑定”(很像将查询绑定到GridView)到Excel文件,以便表中的行占用新Excel文件中的相应单元格,并将文件
更确切地说:我想将查询“绑定”(很像将查询绑定到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