VB.NET 代码 ACCESS导出EXCEL 快速导出不循环
时间: 2024-05-01 07:22:38 浏览: 208
access快速导出excel
4星 · 用户满意度95%
以下是使用 VB.NET 快速导出 ACCESS 数据到 EXCEL 的示例代码:
```
Imports System.Data.OleDb
Imports Excel = Microsoft.Office.Interop.Excel
Public Class Form1
Private Sub btnExport_Click(sender As Object, e As EventArgs) Handles btnExport.Click
Dim connString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\myPath\myDatabase.accdb"
Dim query As String = "SELECT * FROM myTable"
Dim conn As New OleDbConnection(connString)
Dim cmd As New OleDbCommand(query, conn)
Dim da As New OleDbDataAdapter(cmd)
Dim dt As New DataTable()
da.Fill(dt)
Dim excel As New Excel.Application()
Dim workbook As Excel.Workbook = excel.Workbooks.Add(Type.Missing)
Dim worksheet As Excel.Worksheet = Nothing
worksheet = workbook.Sheets("Sheet1")
worksheet = workbook.ActiveSheet
worksheet.Name = "Exported from Access"
Dim columnIndex As Integer = 0
Dim rowIndex As Integer = 1
' Add the headers to the Excel file
For Each dc As DataColumn In dt.Columns
columnIndex += 1
worksheet.Cells(1, columnIndex) = dc.ColumnName
Next
' Add the data to the Excel file
For Each dr As DataRow In dt.Rows
rowIndex += 1
columnIndex = 0
For Each dc As DataColumn In dt.Columns
columnIndex += 1
worksheet.Cells(rowIndex, columnIndex) = dr(dc.ColumnName)
Next
Next
' Format the Excel file
worksheet.Rows("1:1").Font.Bold = True
worksheet.Rows("1:1").AutoFitColumns()
worksheet.Columns.AutoFit()
worksheet.Columns.HorizontalAlignment = Excel.XlHAlign.xlHAlignLeft
' Save the Excel file and close Excel
Dim saveFileDialog As New SaveFileDialog()
saveFileDialog.Filter = "Excel files (*.xlsx)|*.xlsx|All files (*.*)|*.*"
saveFileDialog.FilterIndex = 2
saveFileDialog.RestoreDirectory = True
If saveFileDialog.ShowDialog() = DialogResult.OK Then
workbook.SaveAs(saveFileDialog.FileName)
MessageBox.Show("Export Successful!")
End If
excel.Quit()
End Sub
End Class
```
这个示例代码使用 OleDb 连接到 ACCESS 数据库,从指定的表中获取数据,然后将数据导出到一个新的 EXCEL 文件中。这个示例代码使用了 Microsoft Office Interop Excel 库来创建和操作 EXCEL 文件。
在这个示例代码中,我们首先创建了一个 DataTable 对象来存储从 ACCESS 数据库中获取的数据。然后,我们使用 Excel.Application 类创建了一个新的 EXCEL 文件。我们添加了一个名为 "Sheet1" 的工作表,并将其设置为活动工作表。我们使用循环将数据添加到 Excel 文件中,然后格式化 Excel 文件以使其更易于阅读。最后,我们使用 SaveFileDialog 对象来让用户选择保存文件的位置和文件名,然后将 Excel 文件保存到指定位置。
阅读全文