【发布时间】:2019-12-28 06:45:09
【问题描述】:
为了加快向 Excel 写入值,在 VB.Net 中是否可以将数组写入行而不是值写入单元格?
我尝试了几种方法,要么什么都不写,要么只写数组的第一个值。
任何帮助将不胜感激。
谢谢。
Imports Excel = Microsoft.Office.Interop.Excel
...
Dim Array(2) As String
Array(1) = "Hello"
Array(2) = "World"
...
' Tried several ways one at a time...
objSheet.Cells("C5:C6") = Array
objSheet.Cells("C5:C6").Value = Array
objSheet.Range("C5:C6").Value = Array
objSheet.Range("C5").Value = Array
第一个答案后,这里是修改后的代码
Dim Array(2, 0) As String
Array(0, 0) = "Hello"
Array(1, 0) = "World"
Array(2, 0) = "One"
...
' Test 1
objSheet.Cells("C5:C6").Value = Array 'I get Invalid Parameter (Exception HRESULT : 0x80070057 (E_INVALIDARG))
' Test 2
objxlRange = objSheet.Range("C5:C7") ' Writes Array content as a column (Vertically)
objxlRange.Value = Array
' Test 3
objxlRange = objSheet.Range("C5:E5") ' Writes only first entry 'Hello' in each cell
objxlRange.Value = Array
如何将数组写入一行(水平)?
谢谢
编辑
好的,谢谢,现在可以了!
这是最终的工作代码,供大家分享!
Imports Excel = Microsoft.Office.Interop.Excel
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
' Create an Excel file and write ArrayRow as a Row and ArrayCol as a Column
Dim objApp As Excel.Application
Dim objBook As Excel._Workbook
Dim objBooks As Excel.Workbooks
Dim objSheets As Excel.Sheets
Dim objSheet As Excel._Worksheet
Dim Rng As Excel.Range
Dim StartRow, StartCol
' Array as a Row
Dim ArrayRow(0, 3) As String
ArrayRow(0, 0) = "This"
ArrayRow(0, 1) = "is"
ArrayRow(0, 2) = "a"
ArrayRow(0, 3) = "Row"
' Array as a Column
Dim ArrayCol(3, 0) As String
ArrayCol(0, 0) = "Now"
ArrayCol(1, 0) = "it's"
ArrayCol(2, 0) = "a"
ArrayCol(3, 0) = "Column"
' New instance of Excel and start a new workbook.
objApp = New Excel.Application()
objBooks = objApp.Workbooks
objBook = objBooks.Add
objSheets = objBook.Worksheets
objSheet = objSheets(1)
'Write Array as a Row
StartRow = 1
StartCol = 1
With objSheet
Rng = .Range(.Cells(StartRow, StartCol), _
.Cells(UBound(ArrayRow, 1) - LBound(ArrayRow, 1) + StartRow, _
UBound(ArrayRow, 2) - LBound(ArrayRow, 2) + StartCol))
End With
Rng.Value = ArrayRow ' Row
'Write Array as a Column
StartRow = 3
StartCol = 1
With objSheet
Rng = .Range(.Cells(StartRow, StartCol), _
.Cells(UBound(ArrayCol, 1) - LBound(ArrayCol, 1) + StartRow, _
UBound(ArrayCol, 2) - LBound(ArrayCol, 2) + StartCol))
End With
Rng.Value = ArrayCol ' Column
' Save
objBook.SaveAs("C:\Excel_Range_Test.xls", FileFormat:=56)
objBook.Close()
End Sub
End Class
【问题讨论】: