如何将VB.NET中的数据表传输到Excel

时间:2016-06-17 20:14:52

标签: vb.net excel datatable

我在VB.net中有一个数据表,我试图将其发送到Excel电子表格中的特定范围。但是,在运行程序时,我收到错误:

  

类型' System.Runtime.InteropServices.COMException'的例外情况发生在MeasurementFinder.dll中但未在用户代码中处理

     

附加信息:来自HRESULT的异常: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

我打算做的是遍历给定的数据表,并将表中的值写入电子表格中的一个范围,其左上角由"锚点"范围变量。我没有Visual Stuio的智能感知警告,所以我真的不知道从哪里开始。

提前致谢!

1 个答案:

答案 0 :(得分:1)

targetWs.Range(wRange).Value2 = colm.ColumnName是多余的/错误的。存储在wRange中的Excel范围对象已经是其中包含的工作表的属性。

换句话说,如果您打印出wRange.Parent.Name,您将获得该范围所在的工作表。您无法将范围指向两个不同的工作表(也许可以通过类似范围工会,我从未尝试过,但无论如何,谁会这样做,你可能无法做到...... </streamOfConciousness>

相反,只需使用:

 wrange.value = colm.columnName