VB.NET 结构体数组批量写入Excel
时间: 2024-12-16 14:19:02 浏览: 6
在VB.NET中,使用`Microsoft.Office.Interop.Excel`命名空间下的`Range`和`Application`类,可以方便地将结构体数组批量写入到Excel工作表。这里假设你已经有了一个结构体类型,并且有一个存储了该结构体数组的变量。
首先,你需要安装并引用Microsoft Office Interop Excel库(如果尚未添加,可以在项目管理器的“工具箱”->“引用”中找到并添加)。
以下是一个简单的示例,展示如何将PersonInfo结构体数组写入Excel:
```vb.net
Imports Microsoft.Office.Interop.Excel
Public Class Program
Structure PersonInfo
Public Name As String
Public Age As Integer
End Structure
Sub WriteToExcel()
Dim excelApp As New Application
Dim workbook As Workbook = excelApp.Workbooks.Add()
Dim worksheet As Worksheet = workbook.Sheets(1)
' 创建结构体数组
Dim people(10) As PersonInfo
For i As Integer = 0 To 10
people(i).Name = "Person" & i
people(i).Age = i * 5
Next
' 将数组写入Excel
Dim startRow As Integer = 2 '从第二行开始写入
Dim rng As Range = worksheet.Range("A" & startRow, "B" & (startRow + people.Length - 1))
For Each person In people
Dim nameCell As Range = rng.Cells(0, 1)
nameCell.Value = person.Name
Dim ageCell As Range = rng.Cells(0, 2)
ageCell.Value = person.Age
' 行号+1,因为我们在rng范围的开头位置
rng = rng.Offset(1, 0)
Next
excelApp.Visible = True ' 显示Excel窗口
workbook.Save() ' 保存文件
workbook.Close()
excelApp.Quit()
End Sub
End Class
```
阅读全文