C# 讀取 Excel 文件教程

This article was translated from English: Does it need improvement?
Translated
View the article in English

克里斯蒂安·芬德利

本教程說明如何在C#中讀取Excel文件,以及執行日常任務如數據驗證、數據庫轉換、Web API整合和公式修改。本文引用了使用IronXL .NET Excel庫的代碼示例。


概述

IronXL 方便用 C# 讀取和編輯 Microsoft Excel 文件。IronXL 不需要 Microsoft Excel,也不需要 互操作性事實上, IronXL 提供比 Microsoft.Office.Interop.Excel 更快速且直觀的 API.

IronXL Includes:

  • 我們的 .NET 工程師提供專業產品支持
  • 通過 Microsoft Visual Studio 輕鬆安裝
  • 開發時免費試用測試。許可證從 $749 起。

使用 IronXL 軟體庫,在 C# 和 VB.NET 中讀取和創建 Excel 文件非常簡單。

使用 IronXL 讀取 .XLS 和 .XLSX Excel 文件

以下是使用 IronXL 讀取 Excel 文件的整體工作流程摘要:

  1. 安裝 IronXL Excel 庫。我們可以使用如下方式進行安裝 NuGet 套件 或通過下載 .Net Excel DLL

  2. 使用 WorkBook.Load 方法讀取任何 XLS、XLSX 或 CSV 文件。

  3. 使用直觀的語法獲取單元格值:sheet ["A11"].DecimalValue
:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-1.cs
using IronXL;
using System;
using System.Linq;

// Supported spreadsheet formats for reading include: XLSX, XLS, CSV and TSV
WorkBook workBook = WorkBook.Load("test.xlsx");
WorkSheet workSheet = workBook.WorkSheets.First();

// Select cells easily in Excel notation and return the calculated value
int cellValue = workSheet["A2"].IntValue;

// Read from Ranges of cells elegantly.
foreach (var cell in workSheet["A2:A10"])
{
    Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text);
}

// Advanced Operations
// Calculate aggregate values such as Min, Max and Sum
decimal sum = workSheet["A2:A10"].Sum();

// Linq compatible
decimal max = workSheet["A2:A10"].Max(c => c.DecimalValue);
Imports IronXL
Imports System
Imports System.Linq

' Supported spreadsheet formats for reading include: XLSX, XLS, CSV and TSV
Private workBook As WorkBook = WorkBook.Load("test.xlsx")
Private workSheet As WorkSheet = workBook.WorkSheets.First()

' Select cells easily in Excel notation and return the calculated value
Private cellValue As Integer = workSheet("A2").IntValue

' Read from Ranges of cells elegantly.
For Each cell In workSheet("A2:A10")
	Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text)
Next cell

' Advanced Operations
' Calculate aggregate values such as Min, Max and Sum
Dim sum As Decimal = workSheet("A2:A10").Sum()

' Linq compatible
Dim max As Decimal = workSheet("A2:A10").Max(Function(c) c.DecimalValue)
VB   C#

在本教程下一部分中使用的代碼範例 (以及範例專案代碼) 會處理三個範例 Excel 試算表 (請見下方的視覺效果):


教程

1.免費下載IronXL C# 庫

C# NuGet 程式庫用于 Excel

安裝與 NuGet

Install-Package IronXL.Excel
Java PDF JAR

下載 DLL

下載DLL

手動安裝到您的項目中

C# NuGet 程式庫用于 Excel

安裝與 NuGet

Install-Package IronXL.Excel
Java PDF JAR

下載 DLL

下載DLL

手動安裝到您的項目中

立即開始在您的專案中使用IronPDF,並享受免費試用。

第一步:
green arrow pointer

查看 IronXLNuget 快速安裝和部署。已被下載超過800萬次,它正用C#改變Excel。

C# NuGet 程式庫用于 Excel nuget.org/packages/IronXL.Excel/
Install-Package IronXL.Excel

請考慮安裝 IronXL DLL 直接下載並手動安裝到您的專案或GAC表單: IronXL.zip

手動安裝到您的項目中

下載DLL

首先,我們需要安裝 IronXL.Excel 函式庫,為 .NET 框架添加 Excel 功能。

安裝 IronXL.Excel 最簡便的方法是使用我們的 NuGet 套件,儘管您也可以選擇手動安裝。 DLL 到您的專案或全域組件快取中。

安裝IronXL NuGet 套件

  1. 在Visual Studio中右鍵點擊專案,選擇「管理NuGet套件...」
  2. 搜尋IronXL.Excel套件,然後點擊安裝按鈕將其添加到專案中。

另一種安裝 IronXL 程式庫的方法是使用 NuGet 套件管理器主控台:

  1. 進入套件管理器主控台

  2. 輸入 > Install-Package IronXL.Excel
  PM > Install-Package IronXL.Excel

此外,您可以 在 NuGet 網站上查看套件

手動安裝

或者,我們可以先下載 IronXL .NET Excel DLL 並手動安裝到 Visual Studio。

2. 載入 Excel 工作簿

Workbook 類別表示 Excel 工作表。要使用 C# 開啟 Excel 檔案,我們使用 WorkBook.Load 方法,指定 Excel 檔案的路徑。

:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-2.cs
WorkBook workBook = WorkBook.Load(@"Spreadsheets\\GDP.xlsx");
Dim workBook As WorkBook = WorkBook.Load("Spreadsheets\\GDP.xlsx")
VB   C#

範例:ExcelToDBProcessor

每個 WorkBook 可以有多個 工作表 對象。每個代表 Excel 文件中的一個 Excel 工作表。使用 WorkBook.GetWorkSheet 方法以檢索特定Excel工作表的引用。


:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-3.cs

範例:ExcelToDB

建立新的 Excel 文件

要建立新的 Excel 文件,請使用有效的文件類型來構建新的 WorkBook 對象。

:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-4.cs
WorkBook workBook = new WorkBook(ExcelFileFormat.XLSX);
Dim workBook As New WorkBook(ExcelFileFormat.XLSX)
VB   C#

樣本:ApiToExcelProcessor

注意:使用 ExcelFileFormat.XLS 來支援舊版的 Microsoft Excel (95 及以前).

將工作表新增到 Excel 文件

如前所述,一個 IronXL WorkBook 包含一個或多個 WorkSheet 的集合。

這是一個包含兩個工作表的工作簿在Excel中的樣子。

這是一個包含兩個工作表的工作簿在Excel中的樣子。

若要創建新的 WorkSheet,請使用工作表的名稱調用 WorkBook.CreateWorkSheet

:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-5.cs
WorkSheet workSheet = workBook.GetWorkSheet("GDPByCountry");
Dim workSheet As WorkSheet = workBook.GetWorkSheet("GDPByCountry")
VB   C#

3. 訪問儲存格值

讀取和編輯單個儲存格

訪問單個試算表儲存格的值,是通過從其 WorkSheet 中檢索所需的儲存格來進行的,如下所示:

:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-16.cs
WorkBook workBook = WorkBook.Load("test.xlsx");
WorkSheet workSheet = workBook.DefaultWorkSheet;
IronXL.Cell cell = workSheet["B1"].First();
Dim workBook As WorkBook = WorkBook.Load("test.xlsx")
Dim workSheet As WorkSheet = workBook.DefaultWorkSheet
Dim cell As IronXL.Cell = workSheet("B1").First()
VB   C#

IronXL's 儲存格 class 代表 Excel 試算表中的單一儲存格。它包含屬性和方法,使使用者能夠直接存取和修改儲存格的值。

每個 WorkSheet 物件管理一個 Cell 物件的索引,對應於 Excel 工作表中的每個儲存格值。在上述源代碼中,我們透過其行和列索引引用所需的儲存格。 (在這個情況下, 單元格 B1) 使用標準數組索引語法。

使用對 Cell 對象的引用,我們可以讀取和寫入電子表格單元格中的數據:

:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-17.cs
IronXL.Cell cell = workSheet["B1"].First();
string value = cell.StringValue;   // Read the value of the cell as a string
Console.WriteLine(value);

cell.Value = "10.3289";           // Write a new value to the cell
Console.WriteLine(cell.StringValue);
Dim cell As IronXL.Cell = workSheet("B1").First()
Dim value As String = cell.StringValue ' Read the value of the cell as a string
Console.WriteLine(value)

cell.Value = "10.3289" ' Write a new value to the cell
Console.WriteLine(cell.StringValue)
VB   C#

讀取和寫入單元格範圍的值

Range 類表示 Cell 對象的二維集合。這個集合指的是 Excel 單元格的文字範圍。可以通過在 WorkSheet 對象上使用字符串索引器來獲取範圍。

參數文本可以是單元格的坐標 (例如「A1」,如前所示) 或從左到右、從上到下一範圍的單元格 (例如 "B2:E5")也可以在 WorkSheet 上調用 GetRange

:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-6.cs
Range range = workSheet["D2:D101"];
Dim range As Range = workSheet("D2:D101")
VB   C#

範例:DataValidation

有幾種方法可以讀取或編輯範圍內單元格的值。如果已知數量,請使用 For 迴圈。

:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-7.cs
// Iterate through the rows
for (var y = 2; y <= 101; y++)
{
    var result = new PersonValidationResult { Row = y };
    results.Add(result);

    // Get all cells for the person
    var cells = workSheet[$"A{y}:E{y}"].ToList();

    // Validate the phone number (1 = B)
    var phoneNumber = cells[1].Value;
    result.PhoneNumberErrorMessage = ValidatePhoneNumber(phoneNumberUtil, (string)phoneNumber);

    // Validate the email address (3 = D)
    result.EmailErrorMessage = ValidateEmailAddress((string)cells[3].Value);

    // Get the raw date in the format of Month Day[suffix], Year (4 = E)
    var rawDate = (string)cells[4].Value;
    result.DateErrorMessage = ValidateDate(rawDate);
}
' Iterate through the rows
For y = 2 To 101
	Dim result = New PersonValidationResult With {.Row = y}
	results.Add(result)

	' Get all cells for the person
	Dim cells = workSheet($"A{y}:E{y}").ToList()

	' Validate the phone number (1 = B)
	Dim phoneNumber = cells(1).Value
	result.PhoneNumberErrorMessage = ValidatePhoneNumber(phoneNumberUtil, CStr(phoneNumber))

	' Validate the email address (3 = D)
	result.EmailErrorMessage = ValidateEmailAddress(CStr(cells(3).Value))

	' Get the raw date in the format of Month Day[suffix], Year (4 = E)
	Dim rawDate = CStr(cells(4).Value)
	result.DateErrorMessage = ValidateDate(rawDate)
Next y
VB   C#

範例: DataValidation

向試算表添加公式

使用以下的代码設置Cell的公式 公式 屬性。

以下代碼遍歷每個狀態並在C列中放置百分比總和。

:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-13.cs
// Iterate through all rows with a value
for (var y = 2 ; y < i ; y++)
{
    // Get the C cell
    Cell cell = workSheet[$"C{y}"].First();

    // Set the formula for the Percentage of Total column
    cell.Formula = $"=B{y}/B{i}";
}
' Iterate through all rows with a value
Dim y = 2
Do While y < i
	' Get the C cell
	Dim cell As Cell = workSheet($"C{y}").First()

	' Set the formula for the Percentage of Total column
	cell.Formula = $"=B{y}/B{i}"
	y += 1
Loop
VB   C#

範例:AddFormulaeProcessor

驗證電子表格資料

使用 IronXL 驗證電子表格資料。DataValidation 樣本使用 libphonenumber-csharp 驗證電話號碼,並使用標準的 C# API 驗證電子郵件地址和日期。

:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-8.cs
// Iterate through the rows
for (var i = 2; i <= 101; i++)
{
    var result = new PersonValidationResult { Row = i };
    results.Add(result);

    // Get all cells for the person
    var cells = worksheet[$"A{i}:E{i}"].ToList();

    // Validate the phone number (1 = B)
    var phoneNumber = cells[1].Value;
    result.PhoneNumberErrorMessage = ValidatePhoneNumber(phoneNumberUtil, (string)phoneNumber);

    // Validate the email address (3 = D)
    result.EmailErrorMessage = ValidateEmailAddress((string)cells[3].Value);

    // Get the raw date in the format of Month Day[suffix], Year (4 = E)
    var rawDate = (string)cells[4].Value;
    result.DateErrorMessage = ValidateDate(rawDate);
}
' Iterate through the rows
For i = 2 To 101
	Dim result = New PersonValidationResult With {.Row = i}
	results.Add(result)

	' Get all cells for the person
	Dim cells = worksheet($"A{i}:E{i}").ToList()

	' Validate the phone number (1 = B)
	Dim phoneNumber = cells(1).Value
	result.PhoneNumberErrorMessage = ValidatePhoneNumber(phoneNumberUtil, CStr(phoneNumber))

	' Validate the email address (3 = D)
	result.EmailErrorMessage = ValidateEmailAddress(CStr(cells(3).Value))

	' Get the raw date in the format of Month Day[suffix], Year (4 = E)
	Dim rawDate = CStr(cells(4).Value)
	result.DateErrorMessage = ValidateDate(rawDate)
Next i
VB   C#

上述代碼會遍歷電子表格中的每一行,並將儲存格抓取為列表。每個驗證方法檢查儲存格的值,並在該值無效時返回錯誤訊息。

這段代碼創建一個新的工作表,指定標題,並輸出錯誤訊息結果,以便記錄無效數據的日誌。

:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-9.cs
var resultsSheet = workBook.CreateWorkSheet("Results");
resultsSheet["A1"].Value = "Row";
resultsSheet["B1"].Value = "Valid";
resultsSheet["C1"].Value = "Phone Error";
resultsSheet["D1"].Value = "Email Error";
resultsSheet["E1"].Value = "Date Error";
for (var i = 0; i < results.Count; i++)
{
    var result = results[i];
    resultsSheet[$"A{i + 2}"].Value = result.Row;
    resultsSheet[$"B{i + 2}"].Value = result.IsValid ? "Yes" : "No";
    resultsSheet[$"C{i + 2}"].Value = result.PhoneNumberErrorMessage;
    resultsSheet[$"D{i + 2}"].Value = result.EmailErrorMessage;
    resultsSheet[$"E{i + 2}"].Value = result.DateErrorMessage;
}
workBook.SaveAs(@"Spreadsheets\\PeopleValidated.xlsx");
Dim resultsSheet = workBook.CreateWorkSheet("Results")
resultsSheet("A1").Value = "Row"
resultsSheet("B1").Value = "Valid"
resultsSheet("C1").Value = "Phone Error"
resultsSheet("D1").Value = "Email Error"
resultsSheet("E1").Value = "Date Error"
For i = 0 To results.Count - 1
	Dim result = results(i)
	resultsSheet($"A{i + 2}").Value = result.Row
	resultsSheet($"B{i + 2}").Value = If(result.IsValid, "Yes", "No")
	resultsSheet($"C{i + 2}").Value = result.PhoneNumberErrorMessage
	resultsSheet($"D{i + 2}").Value = result.EmailErrorMessage
	resultsSheet($"E{i + 2}").Value = result.DateErrorMessage
Next i
workBook.SaveAs("Spreadsheets\\PeopleValidated.xlsx")
VB   C#

4. 使用Entity Framework匯出數據

使用 IronXL 將數據導出到數據庫或將 Excel 試算表轉換為數據庫。ExcelToDB 範例會讀取包含各國 GDP 的試算表,然後將數據導出到 SQLite。

它使用 EntityFramework 構建數據庫,然後逐行導出數據。

添加 SQLite Entity Framework NuGet 套件。

EntityFramework允許您建立可將資料匯出到資料庫的模型物件。

:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-10.cs
public class Country
    {
        [Key]
        public Guid Key { get; set; }
        public string Name { get; set; }
        public decimal GDP { get; set; }
    }
Public Class Country
		<Key>
		Public Property Key() As Guid
		Public Property Name() As String
		Public Property GDP() As Decimal
End Class
VB   C#

若要使用不同的資料庫,請安裝相應的 NuGet 套件,並找到 UseSqLite 的等效方法。()```


```cs
:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-11.cs

創建一個 CountryContext,遍歷該範圍來創建每個記錄,然後使用 SaveAsync 將數據提交到資料庫。

:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-12.cs
public async Task ProcessAsync()
{
    //Get the first worksheet
    var workbook = WorkBook.Load(@"Spreadsheets\\GDP.xlsx");
    var worksheet = workbook.GetWorkSheet("GDPByCountry");
    //Create the database connection
    using (var countryContext = new CountryContext())
    {
        //Iterate through all the cells
        for (var i = 2; i <= 213; i++)
        {
            //Get the range from A-B
            var range = worksheet[$"A{i}:B{i}"].ToList();
            //Create a Country entity to be saved to the database
            var country = new Country
            {
                Name = (string)range[0].Value,
                GDP = (decimal)(double)range[1].Value
            };
            //Add the entity
            await countryContext.Countries.AddAsync(country);
        }
        //Commit changes to the database
        await countryContext.SaveChangesAsync();
    }
}
Public Async Function ProcessAsync() As Task
	'Get the first worksheet
	Dim workbook = WorkBook.Load("Spreadsheets\\GDP.xlsx")
	Dim worksheet = workbook.GetWorkSheet("GDPByCountry")
	'Create the database connection
	Using countryContext As New CountryContext()
		'Iterate through all the cells
		For i = 2 To 213
			'Get the range from A-B
			Dim range = worksheet($"A{i}:B{i}").ToList()
			'Create a Country entity to be saved to the database
			Dim country As New Country With {
				.Name = CStr(range(0).Value),
				.GDP = CDec(CDbl(range(1).Value))
			}
			'Add the entity
			Await countryContext.Countries.AddAsync(country)
		Next i
		'Commit changes to the database
		Await countryContext.SaveChangesAsync()
	End Using
End Function
VB   C#

範例:ExcelToDB

5. 從 API 下載數據到電子表格

以下調用使用REST調用 RestClient.Net它下載 JSON 並將其轉換為 RestCountry 類型的 "List"。然後,可以輕鬆遍歷每個國家,並將來自 REST API 的數據保存到 Excel 試算表中。

:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-14.cs
var client = new Client(new Uri("https://restcountries.eu/rest/v2/"));
List<RestCountry> countries = await client.GetAsync<List<RestCountry>>();
Dim client As New Client(New Uri("https://restcountries.eu/rest/v2/"))
Dim countries As List(Of RestCountry) = Await client.GetAsync(Of List(Of RestCountry))()
VB   C#

範例:ApiToExcel

這是 API JSON 資料的樣子。

以下程式碼遍歷國家,並在試算表中設定名稱、人口數、地區、數字代碼以及前三名語言。

:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-15.cs
for (var i = 2; i < countries.Count; i++)
{
    var country = countries[i];
    //Set the basic values
    workSheet[$"A{i}"].Value = country.name;
    workSheet[$"B{i}"].Value = country.population;
    workSheet[$"G{i}"].Value = country.region;
    workSheet[$"H{i}"].Value = country.numericCode;
    //Iterate through languages
    for (var x = 0; x < 3; x++)
    {
        if (x > (country.languages.Count - 1)) break;
        var language = country.languages[x];
        //Get the letter for the column
        var columnLetter = GetColumnLetter(4 + x);
        //Set the language name
        workSheet[$"{columnLetter}{i}"].Value = language.name;
    }
}
For i = 2 To countries.Count - 1
	Dim country = countries(i)
	'Set the basic values
	workSheet($"A{i}").Value = country.name
	workSheet($"B{i}").Value = country.population
	workSheet($"G{i}").Value = country.region
	workSheet($"H{i}").Value = country.numericCode
	'Iterate through languages
	For x = 0 To 2
		If x > (country.languages.Count - 1) Then
			Exit For
		End If
		Dim language = country.languages(x)
		'Get the letter for the column
		Dim columnLetter = GetColumnLetter(4 + x)
		'Set the language name
		workSheet($"{columnLetter}{i}").Value = language.name
	Next x
Next i
VB   C#

物件參考和資源

您也可以找到 IronXL 類別文件 在具有重要價值的物件參考內。

此外,還有其他教程可能會闡明 IronXL.Excel 的其他方面,包括 創建, 打開、寫入、編輯、保存和導出 不使用Excel Interop的XLS、XLSX和CSV文件。

摘要

IronXL.Excel 是唯一可以读取多种电子表格格式的 .NET 软件库。它不需要 微軟 Excel 要安裝,且不依賴於 Interop。

如果您發現這個 .NET 庫在修改 Excel 檔案方面很有用,您可能也會有興趣探索 Google Sheets API 客戶端庫 用於 .NET 的工具,可讓您修改 Google Sheets。


快速指南

下載這個教學作為 C# 原始碼

完整的免費 C# for Excel 原始碼可作為壓縮的 Visual Studio 2017 專案檔案下載。

下載

在 GitHub 上探索此教學

此專案的源代碼在 GitHub 上以 C# 和 VB.NET 提供。

只需幾分鐘即可使用此代碼輕鬆啟動和運行。該項目保存為 Microsoft Visual Studio 2017 項目,但與任何 .NET IDE 兼容。

如何在 GitHub 上使用 C# 讀取 Excel 文件

查看 API 參考文件

查看 IronXL 的 API 參考文件,詳述 IronXL 的所有功能、命名空間、類別、方法字段和列舉。

查看 API 參考文件
.NET 解決方案主管,負責處理 Microsoft Excel 文件 IO

克里斯蒂安·芬德利

軟體開發團隊領導

克里斯蒂安為健康產業開發軟體,並領導一個團隊。克里斯蒂安擁有多年的各類系統整合經驗。IronXL 允許克里斯蒂安匯入和操作來自不同來源的數據,以自動化重複任務和驗證來自第三方來源的輸入數據。