运行以下代码时,我收到一条错误消息,它发生在 rng = .Range.Copy From Recordset 行上。错误是“在 mscorlib.dll 中发生‘System.InvalidCastException’类型的第一次机会异常”。我知道这不是输出,因为注释掉的代码工作正常,尽管速度很慢。我正在研究一种加快速度的方法。这是代码
Private Sub ButRun_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButRun.Click
Dim DWPROD As String = "Data Source=DWPROD;User ID=gayloj01;password=jgay0421;"
Dim Conn As New Oracle.DataAccess.Client.OracleConnection
Dim cmd As New Oracle.DataAccess.Client.OracleCommand
Dim ds As New DataSet
Dim dtAdapter As New Oracle.DataAccess.Client.OracleDataAdapter
Dim Excel As Microsoft.Office.Interop.Excel.Application
Dim rng As Microsoft.Office.Interop.Excel.Range
SQLBuilder()
Conn.ConnectionString = DWPROD
With cmd
.Connection = Conn
.CommandText = strSQL
.CommandType = CommandType.Text
End With
dtAdapter.SelectCommand = cmd
ds.Tables.Add("RawData")
dtAdapter.Fill(ds, "RawData")
Try
Excel = CType(GetObject(, "Excel.Application"), Microsoft.Office.Interop.Excel.Application)
Catch ex As Exception
Excel = New Microsoft.Office.Interop.Excel.Application
End Try
Try
With Excel
.SheetsInNewWorkbook = 1
.Workbooks.Add()
.Worksheets(1).Select()
.Visible = True
.ScreenUpdating = False
rng = .Range(.Cells(1, 1), .Cells(ds.Tables("RawData").Rows.Count, ds.Tables("RawData").Columns.Count))
rng.CopyFromRecordset(ds.Tables("RawData"), ds.Tables("RawData").Rows.Count, ds.Tables("RawData").Columns.Count)
'Dim i As Integer = 1
'For col = 0 To ds.Tables("RawData").Columns.Count - 1
'.Cells(1, i).value = ds.Tables("RawData").Columns(col).ColumnName
'.Cells(1, i).EntireRow.Font.Bold = True
'i += 1
'Next
'i = 2
'Dim j As Integer = 1
'For col = 0 To ds.Tables("RawData").Columns.Count - 1
'i = 2
'For row = 0 To ds.Tables("RawData").Rows.Count - 1
'.Cells(i, j).Value = ds.Tables("RawData").Rows(row).ItemArray(col)
'i += 1
'Next
'j += 1
'Next
.ScreenUpdating = True
End With
Catch ex As Exception
Debug.Print(ex.Message)
End Try
End Sub
我认为这与我如何填充范围有关,但我找不到任何问题。我对 VB.net 很陌生,如果能提供任何帮助,我将不胜感激。
TIA
吉姆·G