如何将VB.NET中的数据表传输到Excel
我在VB.net中有一个数据表,我试图发送到Excel电子表格中的特定范围。 但是,运行该程序时,我得到的错误:
MeasurementFinder.dll中出现“System.Runtime.InteropServices.COMException”types的exception,但未在用户代码中处理
附加信息:来自HRESULT的exception:0x800A03EC
下面的子错误警报:
Private Sub WriteDataTableToRng(targetWs As Excel.Worksheet, anchor As Excel.Range, tbl As System.Data.DataTable) 'This sub writes the given tbl to the targetWs as a range with its top left cell acting as anchor Dim wRange As Excel.Range = anchor 'wRange = write range. This range represents the cell being written to over every iteration For Each colm As DataColumn In tbl.Columns 'This loop writes the column names into the target ws targetWs.Range(wRange).Value2 = colm.ColumnName '**THIS LINE IS CALLED OUT BY THE ERROR wRange = wRange.Offset(0, 1) Next colm wRange = anchor.Offset(1, 0) For Each row As DataRow In tbl.Rows For Each col As DataColumn In tbl.Columns targetWs.Range(wRange).Value2 = tbl.Rows.Item(tbl.Rows.IndexOf(row)).Item(tbl.Columns.IndexOf(col)) '**THIS LINE IS CALLED OUT BY THE SAME ERROR IF THE PREVIOUS LOOP IS COMMENTED OUT Next col Next row End Sub
调用前一个的子节点是:
Private Sub ReportOnTube(TubeID As Integer) 'This sub creates an Excel workbook that acts as a report on a tube, given its ID 'The report has a worksheet for each measurement tied to the tube (From the Gauge DB) 'Verify the tube is in the DB Dim TubeExists As Boolean TubeExists = VerifyTube(TubeID) If TubeExists Then 'Create a new excel workbook and name/time stamp it Dim wb As Excel.Workbook = Me.Application.Workbooks.Add() wb.SaveAs("C:\Gauge Reports\Tube " & TubeID & System.DateTime.Now.ToString(" HH_mm_ss dd-MM-yyyy")) 'Add a worksheet for each measurement tied to the tube Dim ws As Excel.Worksheet ws = wb.Worksheets.Add Dim aRng As Range aRng = ws.Range("B2") TubesConn.Close() TubesConn.Open() Dim selectTbl As New SqlCommand("SELECT * FROM [Tubes]", TubesConn) Dim rdr As SqlDataReader Dim aTbl As New System.Data.DataTable rdr = selectTbl.ExecuteReader() aTbl.Load(rdr) Call WriteDataTableToRng(ws, aRng, aTbl) TubesConn.Close() End If End Sub
我正在使用以下导入:
Imports System.Data.Sql Imports System.Data.SqlClient Imports System.Data Imports System.IO Imports Microsoft.Office.Interop.Excel
我打算做的是迭代通过给定的数据表,并将表中的值写入电子表格中左上angular由“锚点”范围variables给出的范围。 我没有来自Visual Stuio的IntelliSense的警告,所以我不知道从哪一个开始。
提前致谢!
targetWs.Range(wRange).Value2 = colm.ColumnName
是多余的/错误的。 存储在wRange
的excel范围对象已经是包含它的工作表的一个属性。
换句话说,如果你打印出了wRange.Parent.Name
你会得到范围所在的工作表。你不能有一个范围指向两个不同的工作表(也许可以通过像范围联合,我已经从来没有尝试过,但谁会这样做,你可能不能这样做… </streamOfConciousness>
)
相反,只需使用:
wrange.value = colm.columnName