VB.NET 代码 ACCESS导出保存为EXCEL
时间: 2024-05-16 08:18:12 浏览: 157
以下是VB.NET中将ACCESS数据导出到Excel并保存的示例代码:
```vb
Imports System.Data.OleDb
Imports Microsoft.Office.Interop
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'连接Access数据库
Dim connStr As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\mydatabase.accdb"
Dim conn As New OleDbConnection(connStr)
conn.Open()
'查询数据
Dim sql As String = "SELECT * FROM mytable"
Dim cmd As New OleDbCommand(sql, conn)
Dim adapter As New OleDbDataAdapter(cmd)
Dim dt As New DataTable()
adapter.Fill(dt)
'将数据导出到Excel
Dim excelApp As New Excel.Application
Dim workbook As Excel.Workbook = excelApp.Workbooks.Add
Dim worksheet As Excel.Worksheet = workbook.Sheets(1)
'写入表头
For i As Integer = 0 To dt.Columns.Count - 1
worksheet.Cells(1, i + 1) = dt.Columns(i).ColumnName
Next
'写入数据
For i As Integer = 0 To dt.Rows.Count - 1
For j As Integer = 0 To dt.Columns.Count - 1
worksheet.Cells(i + 2, j + 1) = dt.Rows(i)(j).ToString()
Next
Next
'保存Excel文件
workbook.SaveAs("C:\myexcel.xlsx")
workbook.Close()
excelApp.Quit()
'释放资源
Marshal.ReleaseComObject(worksheet)
Marshal.ReleaseComObject(workbook)
Marshal.ReleaseComObject(excelApp)
worksheet = Nothing
workbook = Nothing
excelApp = Nothing
MessageBox.Show("导出成功!")
End Sub
End Class
```
请注意,在运行此代码之前,您需要安装Microsoft Office并添加对Microsoft Excel和Microsoft Access的引用。
阅读全文