# VB.NET 读取和创建 Excel 文件(代码示例教程)
开发人员需要一种流畅、简单的方法来访问 VB .NET Excel 文件。 在这个演练中,我们将使用IronXL读取VB .NET Excel文件并访问项目使用的所有数据。 我们将学习如何创建所有格式的电子表格(`.tsv`),以及使用VB.NET Excel编程设置单元格样式和插入数据。
<div class="hsg-featured-snippet">
<h2>如何在VB.NET中读取Excel文件</h2>
<ol>
<li><a class="js-modal-open" data-modal-id="trial-license-after-download" href="https://nuget.org/packages/IronXL.Excel/">下载 VB.NET 读取 Excel C# 库</a></li>
<li>在VB.NET中创建Excel文件</li>
<li>将数据插入工作表</li>
<li>在VB.NET中读取Excel文件</li>
<li>从工作表中访问数据</li>
<li>对数据执行功能</li>
</ol>
</div>
<hr class="separator" />
<h4 class="tutorial-segment-title">步骤1</h4>
## 1. 适用于 VB.NET 的 Excel 库
使用[DLL 下载](/csharp/excel/packages/IronXL.zip)或[NuGet](https://www.nuget.org/packages/IronXL.Excel)获取 IronXL Excel for VB.NET 库。 IronXL 是我们在 VB.NET 项目中快速访问 Excel 数据的第一步,也是我们将在本教程中使用的工具(开发免费)。
```shell
:ProductInstall
```
<hr class="separator" />
<h4 class="tutorial-segment-title">操作指南</h4>
## 2. 使用 VB.NET 创建 Excel 文件
IronXL提供了在VB.NET项目中创建Excel(`.xlsx`格式)文件的最简单方法。 之后,我们可以插入数据,还可以设置单元格属性,例如字体样式或边框。
### 2.1 创建 Excel 文件
我们先来创建一个工作簿:
```vbnet
' Create a new Excel workbook with the default format (.xlsx)
Dim wb As New WorkBook
```
上述代码用于创建一个新的Excel文件。默认情况下,其扩展名为`.xlsx`。
### 2.2 创建 XLS 文件
如果您希望创建`.xls`扩展文件,可以使用此代码:
```vbnet
' Create a new Excel workbook with .xls format
Dim wb As New WorkBook(ExcelFileFormat.XLS)
```
### 2.3 创建工作表
创建工作簿后,可以按如下方式创建 Excel 工作表:
```vbnet
' Create a new worksheet named "Sheet1" in the workbook
Dim ws1 As WorkSheet = wb.CreateWorkSheet("Sheet1")
```
上述代码将创建一个名为`ws1`在WorkBook `wb`中。
### 2.4 创建多个工作表
可以用同样的方法创建任意数量的工作表:
```vbnet
' Create additional worksheets
Dim ws2 As WorkSheet = wb.CreateWorkSheet("Sheet2")
Dim ws3 As WorkSheet = wb.CreateWorkSheet("Sheet3")
```
<hr class="separator" />
## 3. 将数据插入工作表
### 3.1. 将数据插入单元格
现在我们可以轻松地按如下方式将数据插入工作表单元格:
```vbnet
' Insert a value into a specific cell
worksheet("CellAddress").Value = "MyValue"
```
例如,可以这样插入工作表`ws1`中的数据:
```vbnet
' Insert "Hello World" into cell A1 of the worksheet
ws1("A1").Value = "Hello World"
```
上述代码将在WorkSheet `Hello World`。
### 3.2. 将数据插入范围
也可以使用 range 函数将数据写入多个单元格,如下所示:
```vbnet
' Insert "NewValue" into the range from cell A3 to A8
ws1("A3:A8").Value = "NewValue"
```
### 3.3 创建和编辑工作表示例
我们将创建一个新的Excel文件`Sample.xlsx`,并在其中插入一些数据,以展示我们上面学习到的代码。
```vbnet
' Import IronXL namespace for Excel operations
Imports IronXL
' Main subroutine to create and edit Excel
Sub Main()
' Create a new workbook in XLSX format
Dim wb As New WorkBook(ExcelFileFormat.XLSX)
' Create a worksheet named "Sheet1"
Dim ws1 As WorkSheet = wb.CreateWorkSheet("Sheet1")
' Insert data into cells
ws1("A1").Value = "Hello"
ws1("A2").Value = "World"
' Insert a range of values
ws1("B1:B8").Value = "RangeValue"
' Save the workbook as "Sample.xlsx"
wb.SaveAs("Sample.xlsx")
End Sub
```
**注意:**默认情况下,新创建的Excel文件将位于项目的`bin\Debug`文件夹中。 如果要创建自定义路径下的新文件,请使用:
```vbnet
wb.SaveAs(@"E:\IronXL\Sample.xlsx")
```
这是我们新创建的Excel文件`Sample.xlsx`的截图:
<center>
<div class="center-image-wrapper">
<a rel="nofollow" href="/img/faq/excel/vb-net-excel-files/doc5-1.png" target="_blank"><img src="/img/faq/excel/vb-net-excel-files/doc5-1.png" alt="" class="img-responsive add-shadow" /></a>
</div>
</center>
很明显,使用`IronXL`在VB.NET应用程序中创建Excel文件是多么简单。
<hr class="separator" />
## 4. 在VB.NET中读取Excel文件
IronXL还提供了一种简单的方法在VB .NET项目中读取Excel (`.xlsx`) 文件。 为此,只需获取 Excel 文档,将其加载到您的项目中,读取其数据,并根据您的需要使用它即可。
请遵循以下步骤:
### 4.1. 在项目中访问 Excel 文件
`WorkBook`是IronXL的类,其对象提供对Excel文件及其功能的全面访问。 例如,如果我们想访问 Excel 文件,只需使用:
```vbnet
' Load the Excel file "sample.xlsx" into a workbook
Dim wb As WorkBook = WorkBook.Load("sample.xlsx") 'Excel file path
```
在上述代码中,`wb`。 可以通过访问Excel文件的特定WorkSheets在`wb`上执行任意类型的功能。
### 4.2. 访问特定工作表
要访问Excel中的特定工作表,请使用`WorkSheet`类,可以通过以下不同方式使用:
#### 按图纸名称
```vbnet
' Access worksheet by name
Dim ws As WorkSheet = wb.GetWorkSheet("Sheet1") 'by sheet name
```
#### 按页索引
```vbnet
' Access worksheet by index
Dim ws As WorkSheet = wb.WorkSheets(0) 'by sheet index
```
#### 默认工作表
```vbnet
' Access the default worksheet
Dim ws As WorkSheet = wb.DefaultWorkSheet() 'for the default sheet
```
#### 第一页
```vbnet
' Access the first worksheet in the workbook
Dim sheet As WorkSheet = wb.WorkSheets.FirstOrDefault() 'for the first sheet
```
获得Excel工作表`ws`后,您可以从相应的Excel文件的WorkSheet中获取任何类型的数据,并执行所有Excel功能。
<hr class="separator" />
## 5. 从工作表中访问数据
可以这样从ExcelSheet `ws`中访问数据:
```vbnet
' Retrieve values from specific cells
Dim int_Value As Integer = ws("A2").IntValue 'for integer
Dim str_value As String = ws("A2").ToString() 'for string
```
### 5.1. 特定列的数据
也可以通过以下方式从特定列的多个单元格中获取数据:
```vbnet
' Loop through cells in a specific range and print their values
For Each cell In ws("A2:A10")
Console.WriteLine("value is: {0}", cell.Text)
Next cell
```
它将显示从单元格`A10`的值。 下面给出上述讨论的代码示例。
```vbnet
' Example: Load and display values from a column
Imports IronXL
Sub Main()
' Load the workbook from file
Dim wb As WorkBook = WorkBook.Load("sample.xlsx")
' Get the first worksheet
Dim ws As WorkSheet = wb.WorkSheets.FirstOrDefault()
' Loop through cells in range A2:A10
For Each cell In ws("A2:A10")
Console.WriteLine("value is: {0}", cell.Text)
Next
Console.ReadKey()
End Sub
```
这将显示以下输出:
<center>
<div class="center-image-wrapper">
<a rel="nofollow" href="/img/faq/excel/vb-net-excel-files/doc3-input1.png" target="_blank"><img src="/img/faq/excel/vb-net-excel-files/doc3-input1.png" alt="" class="img-responsive add-shadow" /></a>
</div>
</center>
我们可以看到Excel文件`Sample.xlsx`的截图:
<center>
<div class="center-image-wrapper">
<a rel="nofollow" href="/img/faq/excel/vb-net-excel-files/doc3-1.png" target="_blank"><img src="/img/faq/excel/vb-net-excel-files/doc3-1.png" alt="" class="img-responsive add-shadow" /></a>
</div>
</center>
<hr class="separator" />
## 6. 对数据执行函数
通过应用 SUM、MIN 或 MAX 等聚合函数,可以轻松地从 Excel 工作表中访问筛选后的数据,方法如下:
```vbnet
' Aggregate functions on a range of data
Dim sum As Decimal = ws("From:To").Sum()
Dim min As Decimal = ws("From:To").Min()
Dim max As Decimal = ws("From:To").Max()
```
您可以点击此处阅读更多关于[Excel聚合函数的信息](https://ironsoftware.com/csharp/excel/tutorials/csharp-open-write-excel-file/#sample-function-sum)。
```vbnet
' Example: Apply functions to data
Imports IronXL
Sub Main()
' Load the workbook
Dim wb As WorkBook = WorkBook.Load("sample.xlsx")
' Get the first worksheet
Dim ws As WorkSheet = wb.WorkSheets.FirstOrDefault()
' Perform aggregate calculations
Dim sum As Decimal = ws("G2:G10").Sum()
Dim min As Decimal = ws("G2:G10").Min()
Dim max As Decimal = ws("G2:G10").Max()
' Print the results
Console.WriteLine("Sum is: {0}", sum)
Console.WriteLine("Min is: {0}", min)
Console.WriteLine("Max is: {0}", max)
Console.ReadKey()
End Sub
```
这段代码会显示如下内容:
<center>
<div class="center-image-wrapper">
<a rel="nofollow" href="/img/faq/excel/vb-net-excel-files/doc3-output2.png" target="_blank"><img src="/img/faq/excel/vb-net-excel-files/doc3-output2.png" alt="" class="img-responsive add-shadow" /></a>
</div>
</center>
以及这个Excel文件`Sample.xlsx`:
<center>
<div class="center-image-wrapper">
<a rel="nofollow" href="/img/faq/excel/vb-net-excel-files/doc3-2.png" target="_blank"><img src="/img/faq/excel/vb-net-excel-files/doc3-2.png" alt="" class="img-responsive add-shadow" /></a>
</div>
</center>
您可以通过链接的文章了解更多关于如何[阅读Excel的信息](https://ironsoftware.com/csharp/excel/#read-excel)。
<hr class="separator" />
<h4 class="tutorial-segment-title">教程快速访问</h4>
<div class="tutorial-section">
<div class="row">
<div class="col-sm-8">
<h3>文档 API 参考</h3>
<p>访问 IronXL 的 API 参考文档,了解如何在 VB.NET 项目中轻松使用 Excel。查找功能、函数、类等列表。 </p>
<a class="doc-link" href="/csharp/excel/object-reference/api/" target="_blank"> 文档 API 参考 <i class="fa fa-chevron-right"></i></a>
</div>
<div class="col-sm-4">
<div class="tutorial-image">
<img style="max-width: 110px; width: 100px; height: 140px;" alt="" class="img-responsive add-shadow" src="/img/svgs/documentation.svg" width="100" height="140" />
</div>
</div>
</div>
</div>
' Import IronXL namespace for Excel operationsImportsIronXL' Main subroutine to create and edit ExcelSubMain() ' Create a new workbook in XLSX format Dim wb As New WorkBook(ExcelFileFormat.XLSX) ' Create a worksheet named "Sheet1" Dim ws1 AsWorkSheet = wb.CreateWorkSheet("Sheet1") ' Insert data into cells ws1("A1").Value = "Hello" ws1("A2").Value = "World" ' Insert a range of values ws1("B1:B8").Value = "RangeValue" ' Save the workbook as "Sample.xlsx" wb.SaveAs("Sample.xlsx")End Sub
' Import IronXL namespace for Excel operations
Imports IronXL
' Main subroutine to create and edit Excel
Sub Main()
' Create a new workbook in XLSX format
Dim wb As New WorkBook(ExcelFileFormat.XLSX)
' Create a worksheet named "Sheet1"
Dim ws1 As WorkSheet = wb.CreateWorkSheet("Sheet1")
' Insert data into cells
ws1("A1").Value = "Hello"
ws1("A2").Value = "World"
' Insert a range of values
ws1("B1:B8").Value = "RangeValue"
' Save the workbook as "Sample.xlsx"
wb.SaveAs("Sample.xlsx")
End Sub
' Retrieve values from specific cellsDim int_Value AsInteger = ws("A2").IntValue'for integerDim str_value AsString = ws("A2").ToString() 'for string
' Retrieve values from specific cells
Dim int_Value As Integer = ws("A2").IntValue 'for integer
Dim str_value As String = ws("A2").ToString() 'for string
VB .NET
5.1. 特定列的数据
也可以通过以下方式从特定列的多个单元格中获取数据:
' Loop through cells in a specific range and print their valuesFor Each cell In ws("A2:A10")Console.WriteLine("value is: {0}", cell.Text)Next cell
' Loop through cells in a specific range and print their values
For Each cell In ws("A2:A10")
Console.WriteLine("value is: {0}", cell.Text)
Next cell
VB .NET
它将显示从单元格A10的值。 下面给出上述讨论的代码示例。
' Example: Load and display values from a columnImportsIronXLSubMain() ' Load the workbook from file Dim wb AsWorkBook = WorkBook.Load("sample.xlsx") ' Get the first worksheet Dim ws AsWorkSheet = wb.WorkSheets.FirstOrDefault() ' Loop through cells in range A2:A10 For Each cell In ws("A2:A10")Console.WriteLine("value is: {0}", cell.Text) NextConsole.ReadKey()End Sub
' Example: Load and display values from a column
Imports IronXL
Sub Main()
' Load the workbook from file
Dim wb As WorkBook = WorkBook.Load("sample.xlsx")
' Get the first worksheet
Dim ws As WorkSheet = wb.WorkSheets.FirstOrDefault()
' Loop through cells in range A2:A10
For Each cell In ws("A2:A10")
Console.WriteLine("value is: {0}", cell.Text)
Next
Console.ReadKey()
End Sub
VB .NET
这将显示以下输出:
我们可以看到Excel文件Sample.xlsx的截图:
6. 对数据执行函数
通过应用 SUM、MIN 或 MAX 等聚合函数,可以轻松地从 Excel 工作表中访问筛选后的数据,方法如下:
' Aggregate functions on a range of dataDim sum AsDecimal = ws("From:To").Sum()Dim min AsDecimal = ws("From:To").Min()Dim max AsDecimal = ws("From:To").Max()
' Aggregate functions on a range of data
Dim sum As Decimal = ws("From:To").Sum()
Dim min As Decimal = ws("From:To").Min()
Dim max As Decimal = ws("From:To").Max()
' Example: Apply functions to dataImportsIronXLSubMain() ' Load the workbook Dim wb AsWorkBook = WorkBook.Load("sample.xlsx") ' Get the first worksheet Dim ws AsWorkSheet = wb.WorkSheets.FirstOrDefault() ' Perform aggregate calculations Dim sum AsDecimal = ws("G2:G10").Sum() Dim min AsDecimal = ws("G2:G10").Min() Dim max AsDecimal = ws("G2:G10").Max() ' Print the resultsConsole.WriteLine("Sum is: {0}", sum)Console.WriteLine("Min is: {0}", min)Console.WriteLine("Max is: {0}", max)Console.ReadKey()End Sub
' Example: Apply functions to data
Imports IronXL
Sub Main()
' Load the workbook
Dim wb As WorkBook = WorkBook.Load("sample.xlsx")
' Get the first worksheet
Dim ws As WorkSheet = wb.WorkSheets.FirstOrDefault()
' Perform aggregate calculations
Dim sum As Decimal = ws("G2:G10").Sum()
Dim min As Decimal = ws("G2:G10").Min()
Dim max As Decimal = ws("G2:G10").Max()
' Print the results
Console.WriteLine("Sum is: {0}", sum)
Console.WriteLine("Min is: {0}", min)
Console.WriteLine("Max is: {0}", max)
Console.ReadKey()
End Sub