请问如何实现将数据库中的数据输出到excel的出错问题
在编写代码前我有选择了com对应的组件,我的excel是2003.下面就是相关代码,当我运行时提示出错说: 未处理的“System.Runtime.InteropServices.COMException”类型的异常出现在 sunrise.exe 中。
其他信息: HRESULT 中的异常:0x800A03EC。
而代码出错处是:AppExcel.Application.Workbooks.Add(True)
请问具体是什么原因呢?还是我的方法是错误的呢?谢谢!!!!!!!!!!!!!!!!!!!
详细代码如下:
Dim myDataSet As DataSet = New DataSet
'连接数据库,得到数据集
Try
' 设定数据连接字符串,此字符串的意思是打开Sql server数据库,服务器名称为本地 ,数据库为temp
Dim strCon As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\sunrise\sr.mdb"
'数据连接代码,对此修改可导入其他类型数据库到Excle表格
Dim myConn As OleDbConnection = New OleDbConnection(strCon)
myConn.Open()
Dim strCom As String = "SELECT * FROM worker"
Dim myCommand As OleDbDataAdapter = New OleDbDataAdapter(strCom, myConn)
myCommand.Fill(myDataSet, "worker")
'关闭此OleDbConnection
myConn.Close()
Catch ey As Exception
MessageBox.Show("连接错误! " + ey.ToString(), "错误")
End Try
Dim table As DataTable = myDataSet.Tables("worker")
'创建一个空的Excel电子表格文档
Dim AppExcel As Excel.Application = New Excel.Application
AppExcel.Visible = True
AppExcel.Application.Workbooks.Add(True)
'读取数据的字段名称,并在产生的Excel表格的第一行显示出来
Dim colIndex As Integer = 0
Dim col As DataColumn = New DataColumn
For Each col In table.Columns
colIndex = colIndex + 1
AppExcel.Cells(1, colIndex) = col.ColumnName
Next
'实现数据集到Excel表格的转换
Dim rowIndex As Integer = 1
Dim row As DataRow
For Each row In table.Rows
rowIndex = rowIndex + 1
colIndex = 0
Dim col1 As DataColumn
For Each col1 In table.Columns
colIndex = colIndex + 1
AppExcel.Cells(rowIndex, colIndex) = row(col1.ColumnName).ToString()
Next
Next
AppExcel.Visible = True