vb.net中,新建一个excel文件,将A1到C1单元格合并,内容是文件名,A2值是‘序号’,B2的值是‘名称’,A2值是‘数量’, 从第三行开始,将一个二维数组写入单元格中,请给出一个完整vb.net代码示例
时间: 2024-10-21 15:17:50 浏览: 33
在VB.NET中,你可以使用Microsoft.Office.Interop.Excel库来操作Excel文件。以下是一个完整的代码示例,它展示了如何按照你的需求创建一个新的Excel文件,并填写数据:
```vb.net
Imports Microsoft.Office.Interop.Excel
Public Sub CreateExcelFile(fileName As String, data As Integer(,))
' 创建Excel应用对象
Dim excelApp As New Application
Try
' 激活Excel并创建新工作簿
Dim workbook As Workbook = excelApp.Workbooks.Add()
Dim worksheet As Worksheet = workbook.Sheets(1)
' 设置标题行
worksheet.Cells(1, 1).Value = "文件名"
worksheet.Cells(1, 2).Value = "序号"
worksheet.Cells(1, 3).Value = "名称"
worksheet.Cells(1, 4).Value = "数量"
' 合并单元格 A1到C1
Dim rangeStart As Range = worksheet.Range("A1:C1")
rangeStart.Merge()
' 写入文件名
Dim fileRange As Range = worksheet.Cells(1, 1)
fileRange.Value = fileName
' 写入数据到第二行及之后
For i As Integer = 0 To data.GetLength(0) - 1
Dim row As Integer = 2 + i
worksheet.Cells(row, 1).Value = i + 2 ' 序号
worksheet.Cells(row, 2).Value = data(i, 0) ' 名称
worksheet.Cells(row, 3).Value = data(i, 1) ' 数量
Next
' 保存并关闭工作簿
workbook.SaveAs(fileName & ".xlsx", XlFileFormat.xlOpenXMLWorkbook) ' 或者你喜欢的其他格式
workbook.Close(SaveChanges:=True)
Catch ex As Exception
Console.WriteLine("Error: " & ex.Message)
Finally
' 关闭应用释放资源
If Not excelApp Is Nothing Then
excelApp.Quit()
End If
End Try
End Sub
```
阅读全文