How to Read Excel Files in C# Without Interop: Complete Developer Guide
透過 IronXL 掌握 C# 中的 Excel 檔案處理技巧——這款強大的 .NET 程式庫能讀取、驗證及匯出試算表資料,且無需安裝 Microsoft Office。 這份全面的教學指南示範了實用的 Excel 操作,包括資料驗證、資料庫轉換以及 REST API 整合。
快速入門:使用 IronXL 在一行內讀取儲存格
只需一行程式碼,您即可透過 IronXL 載入 Excel 工作簿並擷取儲存格的值。 其設計以簡便性為宗旨——無需 Interop,無需複雜設定——僅需快速存取您的資料。
如何在 C# 中設定 IronXL 以讀取 Excel 檔案?
在您的 C# 專案中設定 IronXL 以讀取 Excel 檔案,只需幾分鐘即可完成。 此函式庫同時支援 .XLS 與 .XLSX 格式,使其能靈活應對任何與 Excel 相關的任務。
請按照以下步驟開始:
- 下載 C# 函式庫以讀取 Excel 檔案
- 使用
WorkBook.Load()載入並讀取 Excel 工作簿 - 使用
GetWorkSheet()方法存取工作表 - 使用直觀的語法(如
sheet["A1"].Value)讀取儲存格值 - 透過程式化方式驗證與處理試算表資料
- 使用 Entity Framework 將資料匯出至資料庫
IronXL 擅長使用 C# 讀取及編輯 Microsoft Excel 文件。 此函式庫可獨立運作——其運作既不需要 Microsoft Excel,也不需要 Interop。 事實上,IronXL 提供的 API 比 Microsoft.Office.Interop.Excel 更快且更直觀。
IronXL 包含:
- 由我們的 .NET 工程師提供專屬的產品支援
- 透過 Microsoft Visual Studio 輕鬆安裝
- 開發用免費試用版。 來自
liteLicense的授權
透過 IronXL 程式庫,在 C# 和 VB.NET 中讀取及建立 Excel 檔案變得輕而易舉。
使用 IronXL 讀取 .XLS 和 .XLSX Excel 檔案
以下是使用 IronXL 讀取 Excel 檔案的基本工作流程:
- 透過 NuGet 套件安裝 IronXL Excel 程式庫,或下載 .NET Excel DLL
- 使用
WorkBook.Load()方法讀取任何 XLS、XLSX 或 CSV 文件 - 使用直觀的語法存取儲存格值:
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;
// Load Excel workbook from file path
WorkBook workBook = WorkBook.Load("test.xlsx");
// Access the first worksheet using LINQ
WorkSheet workSheet = workBook.WorkSheets.First();
// Read integer value from cell A2
int cellValue = workSheet["A2"].IntValue;
Console.WriteLine($"Cell A2 value: {cellValue}");
// Iterate through a range of cells
foreach (var cell in workSheet["A2:A10"])
{
Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text);
}
// Advanced Operations with LINQ
// Calculate sum using built_in Sum() method
decimal sum = workSheet["A2:A10"].Sum();
// Find maximum value using LINQ
decimal max = workSheet["A2:A10"].Max(c => c.DecimalValue);
// Output calculated results
Console.WriteLine($"Sum of A2:A10: {sum}");
Console.WriteLine($"Maximum value: {max}");
Imports IronXL
Imports System
Imports System.Linq
' Load Excel workbook from file path
Dim workBook As WorkBook = WorkBook.Load("test.xlsx")
' Access the first worksheet using LINQ
Dim workSheet As WorkSheet = workBook.WorkSheets.First()
' Read integer value from cell A2
Dim cellValue As Integer = workSheet("A2").IntValue
Console.WriteLine($"Cell A2 value: {cellValue}")
' Iterate through a range of cells
For Each cell In workSheet("A2:A10")
Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text)
Next
' Advanced Operations with LINQ
' Calculate sum using built_in Sum() method
Dim sum As Decimal = workSheet("A2:A10").Sum()
' Find maximum value using LINQ
Dim max As Decimal = workSheet("A2:A10").Max(Function(c) c.DecimalValue)
' Output calculated results
Console.WriteLine($"Sum of A2:A10: {sum}")
Console.WriteLine($"Maximum value: {max}")
此程式碼展示了 IronXL 的幾項關鍵功能:載入工作簿、透過位址存取儲存格、遍歷範圍,以及執行計算。 WorkBook.Load() 方法能智慧型地偵測檔案格式,而範圍語法 ["A2:A10"] 則提供類似 Excel 的儲存格選取功能。 透過 LINQ 整合,可在儲存格集合上執行強大的資料查詢與彙總操作。
本教學中的程式碼範例使用三個 Excel 試算表範例,用以展示不同的資料情境:
本教學中用於演示各種 IronXL 操作的範例 Excel 檔案(GDP.xlsx、People.xlsx 及 PopulationByState.xlsx)。
如何安裝 IronXL C# 程式庫?
安裝 IronXl.Excel 函式庫,可為您的 .NET Framework 專案增添全面的 Excel 功能。 可選擇透過 NuGet 安裝或手動整合 DLL 檔案。
安裝 IronXL NuGet 套件
- 在 Visual Studio 中,右鍵點擊您的專案,然後選擇"管理 NuGet 套件..."
- 在"瀏覽"索引標籤中搜尋
IronXl.Excel - 點擊"安裝"按鈕,將 IronXL 加入您的專案
透過 Visual Studio 的 NuGet 套件管理員安裝 IronXL,可提供自動的依賴項管理。
或者,您也可以透過套件管理主控台安裝 IronXL:
- 開啟套件管理員主控台(工具 → NuGet 套件管理員 → 套件管理員主控台)
- 執行安裝指令:
Install-Package IronXL.Excel
手動安裝
若需手動安裝,請下載 IronXL for .NET Excel DLL 檔案,並直接在您的 Visual Studio 專案中引用該檔案。
如何載入並讀取 Excel 工作簿?
WorkBook 類別代表整個 Excel 檔案。請使用 WorkBook.Load() 方法載入 Excel 檔案,該方法接受 XLS、XLSX、CSV 及 TSV 格式的檔案路徑。
:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-2.cs
using IronXL;
using System;
using System.Linq;
// Load Excel file from specified path
WorkBook workBook = WorkBook.Load(@"Spreadsheets\GDP.xlsx");
Console.WriteLine("Workbook loaded successfully.");
// Access specific worksheet by name
WorkSheet sheet = workBook.GetWorkSheet("Sheet1");
// Read and display cell value
string cellValue = sheet["A1"].StringValue;
Console.WriteLine($"Cell A1 contains: {cellValue}");
// Perform additional operations
// Count non_empty cells in column A
int rowCount = sheet["A:A"].Count(cell => !cell.IsEmpty);
Console.WriteLine($"Column A has {rowCount} non_empty cells");
Imports IronXL
Imports System
Imports System.Linq
' Load Excel file from specified path
Dim workBook As WorkBook = WorkBook.Load("Spreadsheets\GDP.xlsx")
Console.WriteLine("Workbook loaded successfully.")
' Access specific worksheet by name
Dim sheet As WorkSheet = workBook.GetWorkSheet("Sheet1")
' Read and display cell value
Dim cellValue As String = sheet("A1").StringValue
Console.WriteLine($"Cell A1 contains: {cellValue}")
' Perform additional operations
' Count non_empty cells in column A
Dim rowCount As Integer = sheet("A:A").Count(Function(cell) Not cell.IsEmpty)
Console.WriteLine($"Column A has {rowCount} non_empty cells")
每個 WorkBook 包含多個 WorkSheet 物件,代表個別的 Excel 試算表。 使用 GetWorkSheet() 透過名稱存取工作表:
:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-3.cs
using IronXL;
using System;
// Get worksheet by name
WorkSheet workSheet = workBook.GetWorkSheet("GDPByCountry");
Console.WriteLine("Worksheet 'GDPByCountry' not found");
// List available worksheets
foreach (var sheet in workBook.WorkSheets)
{
Console.WriteLine($"Available: {sheet.Name}");
}
Imports IronXL
Imports System
' Get worksheet by name
Dim workSheet As WorkSheet = workBook.GetWorkSheet("GDPByCountry")
Console.WriteLine("Worksheet 'GDPByCountry' not found")
' List available worksheets
For Each sheet In workBook.WorkSheets
Console.WriteLine($"Available: {sheet.Name}")
Next
如何在 C# 中建立新的 Excel 文件?
透過建立具有您所需檔案格式的 WorkBook 物件,來建立新的 Excel 文件。 IronXL 同時支援現代的 XLSX 格式與傳統的 XLS 格式。
:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-4.cs
using IronXL;
// Create new XLSX workbook (recommended format)
WorkBook workBook = WorkBook.Create(ExcelFileFormat.XLSX);
// Set workbook metadata
workBook.Metadata.Author = "Your Application";
workBook.Metadata.Comments = "Generated by IronXL";
// Create new XLS workbook for legacy support
WorkBook legacyWorkBook = WorkBook.Create(ExcelFileFormat.XLS);
// Save the workbook
workBook.SaveAs("NewDocument.xlsx");
Imports IronXL
' Create new XLSX workbook (recommended format)
Private workBook As WorkBook = WorkBook.Create(ExcelFileFormat.XLSX)
' Set workbook metadata
workBook.Metadata.Author = "Your Application"
workBook.Metadata.Comments = "Generated by IronXL"
' Create new XLS workbook for legacy support
Dim legacyWorkBook As WorkBook = WorkBook.Create(ExcelFileFormat.XLS)
' Save the workbook
workBook.SaveAs("NewDocument.xlsx")
注意:僅在需要與 Excel 2003 及更早版本相容時,才使用 ExcelFileFormat.XLS。
如何將工作表新增至 Excel 文件中?
一個 IronXL WorkBook 包含一組工作表。 理解此結構有助於建立多工作表的 Excel 檔案。
IronXL 中包含多個工作表物件的工作簿結構之視覺化呈現。
using CreateWorkSheet() 建立新的工作表:
:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-5.cs
using IronXL;
// Create multiple worksheets with descriptive names
WorkSheet summarySheet = workBook.CreateWorkSheet("Summary");
WorkSheet dataSheet = workBook.CreateWorkSheet("RawData");
WorkSheet chartSheet = workBook.CreateWorkSheet("Charts");
// Set the active worksheet
workBook.SetActiveTab(0); // Makes "Summary" the active sheet
// Access default worksheet (first sheet)
WorkSheet defaultSheet = workBook.DefaultWorkSheet;
Imports IronXL
' Create multiple worksheets with descriptive names
Dim summarySheet As WorkSheet = workBook.CreateWorkSheet("Summary")
Dim dataSheet As WorkSheet = workBook.CreateWorkSheet("RawData")
Dim chartSheet As WorkSheet = workBook.CreateWorkSheet("Charts")
' Set the active worksheet
workBook.SetActiveTab(0) ' Makes "Summary" the active sheet
' Access default worksheet (first sheet)
Dim defaultSheet As WorkSheet = workBook.DefaultWorkSheet
如何讀取和編輯儲存格值?
讀取與編輯單一儲存格
透過工作表的 indexer 屬性存取個別儲存格。 IronXL 的 Cell 類別提供強類型化的值屬性。
:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-6.cs
using IronXL;
using System;
using System.Linq;
// Load workbook and get worksheet
WorkBook workBook = WorkBook.Load("test.xlsx");
WorkSheet workSheet = workBook.DefaultWorkSheet;
// Access cell B1
IronXL.Cell cell = workSheet["B1"].First();
// Read cell value with type safety
string textValue = cell.StringValue;
int intValue = cell.IntValue;
decimal decimalValue = cell.DecimalValue;
DateTime? dateValue = cell.DateTimeValue;
// Check cell data type
if (cell.IsNumeric)
{
Console.WriteLine($"Numeric value: {cell.DecimalValue}");
}
else if (cell.IsText)
{
Console.WriteLine($"Text value: {cell.StringValue}");
}
Imports IronXL
Imports System
Imports System.Linq
' Load workbook and get worksheet
Dim workBook As WorkBook = WorkBook.Load("test.xlsx")
Dim workSheet As WorkSheet = workBook.DefaultWorkSheet
' Access cell B1
Dim cell As IronXL.Cell = workSheet("B1").First()
' Read cell value with type safety
Dim textValue As String = cell.StringValue
Dim intValue As Integer = cell.IntValue
Dim decimalValue As Decimal = cell.DecimalValue
Dim dateValue As DateTime? = cell.DateTimeValue
' Check cell data type
If cell.IsNumeric Then
Console.WriteLine($"Numeric value: {cell.DecimalValue}")
ElseIf cell.IsText Then
Console.WriteLine($"Text value: {cell.StringValue}")
End If
Cell 類別提供適用於不同資料類型的多種屬性,並會在可能的情況下自動轉換數值。 如需更多儲存格操作功能,請參閱《儲存格格式設定教學》。
:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-7.cs
// Write different data types to cells
workSheet["A1"].Value = "Product Name"; // String
workSheet["B1"].Value = 99.95m; // Decimal
workSheet["C1"].Value = DateTime.Today; // Date
workSheet["D1"].Formula = "=B1*1.2"; // Formula
// Format cells
workSheet["B1"].FormatString = "$#,##0.00"; // Currency format
workSheet["C1"].FormatString = "yyyy-MM-dd";// Date format
// Save changes
workBook.Save();
' Write different data types to cells
workSheet("A1").Value = "Product Name" ' String
workSheet("B1").Value = 99.95D ' Decimal
workSheet("C1").Value = DateTime.Today ' Date
workSheet("D1").Formula = "=B1*1.2" ' Formula
' Format cells
workSheet("B1").FormatString = "$#,##0.00" ' Currency format
workSheet("C1").FormatString = "yyyy-MM-dd" ' Date format
' Save changes
workBook.Save()
如何處理儲存格範圍?
Range 類別代表一組儲存格集合,可對 Excel 資料執行批次操作。
:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-8.cs
using IronXL;
using Range = IronXL.Range;
// Select range using Excel notation
Range range = workSheet["D2:D101"];
// Alternative: Use Range class for dynamic selection
Range dynamicRange = workSheet.GetRange("D2:D101"); // Row 2_101, Column D
// Perform bulk operations
range.Value = 0; // Set all cells to 0
Imports IronXL
' Select range using Excel notation
Dim range As Range = workSheet("D2:D101")
' Alternative: Use Range class for dynamic selection
Dim dynamicRange As Range = workSheet.GetRange("D2:D101") ' Row 2_101, Column D
' Perform bulk operations
range.Value = 0 ' Set all cells to 0
當已知儲存格數量時,可透過迴圈高效處理資料範圍:
// Data validation example
public class ValidationResult
{
public int Row { get; set; }
public string PhoneError { get; set; }
public string EmailError { get; set; }
public string DateError { get; set; }
public bool IsValid => string.IsNullOrEmpty(PhoneError) &&
string.IsNullOrEmpty(EmailError) &&
string.IsNullOrEmpty(DateError);
}
// Validate data in rows 2-101
var results = new List<ValidationResult>();
for (int row = 2; row <= 101; row++)
{
var result = new ValidationResult { Row = row };
// Get row data efficiently
var phoneCell = workSheet[$"B{row}"];
var emailCell = workSheet[$"D{row}"];
var dateCell = workSheet[$"E{row}"];
// Validate phone number
if (!IsValidPhoneNumber(phoneCell.StringValue))
result.PhoneError = "Invalid phone format";
// Validate email
if (!IsValidEmail(emailCell.StringValue))
result.EmailError = "Invalid email format";
// Validate date
if (!dateCell.IsDateTime)
result.DateError = "Invalid date format";
results.Add(result);
}
// Helper methods
bool IsValidPhoneNumber(string phone) =>
System.Text.RegularExpressions.Regex.IsMatch(phone, @"^\d{3}-\d{3}-\d{4}$");
bool IsValidEmail(string email) =>
email.Co/ntains("@") && email.Co/ntains(".");
// Data validation example
public class ValidationResult
{
public int Row { get; set; }
public string PhoneError { get; set; }
public string EmailError { get; set; }
public string DateError { get; set; }
public bool IsValid => string.IsNullOrEmpty(PhoneError) &&
string.IsNullOrEmpty(EmailError) &&
string.IsNullOrEmpty(DateError);
}
// Validate data in rows 2-101
var results = new List<ValidationResult>();
for (int row = 2; row <= 101; row++)
{
var result = new ValidationResult { Row = row };
// Get row data efficiently
var phoneCell = workSheet[$"B{row}"];
var emailCell = workSheet[$"D{row}"];
var dateCell = workSheet[$"E{row}"];
// Validate phone number
if (!IsValidPhoneNumber(phoneCell.StringValue))
result.PhoneError = "Invalid phone format";
// Validate email
if (!IsValidEmail(emailCell.StringValue))
result.EmailError = "Invalid email format";
// Validate date
if (!dateCell.IsDateTime)
result.DateError = "Invalid date format";
results.Add(result);
}
// Helper methods
bool IsValidPhoneNumber(string phone) =>
System.Text.RegularExpressions.Regex.IsMatch(phone, @"^\d{3}-\d{3}-\d{4}$");
bool IsValidEmail(string email) =>
email.Co/ntains("@") && email.Co/ntains(".");
Imports System.Text.RegularExpressions
Imports System.Collections.Generic
' Data validation example
Public Class ValidationResult
Public Property Row As Integer
Public Property PhoneError As String
Public Property EmailError As String
Public Property DateError As String
Public ReadOnly Property IsValid As Boolean
Get
Return String.IsNullOrEmpty(PhoneError) AndAlso
String.IsNullOrEmpty(EmailError) AndAlso
String.IsNullOrEmpty(DateError)
End Get
End Property
End Class
' Validate data in rows 2-101
Dim results As New List(Of ValidationResult)()
For row As Integer = 2 To 101
Dim result As New ValidationResult With {.Row = row}
' Get row data efficiently
Dim phoneCell = workSheet($"B{row}")
Dim emailCell = workSheet($"D{row}")
Dim dateCell = workSheet($"E{row}")
' Validate phone number
If Not IsValidPhoneNumber(phoneCell.StringValue) Then
result.PhoneError = "Invalid phone format"
End If
' Validate email
If Not IsValidEmail(emailCell.StringValue) Then
result.EmailError = "Invalid email format"
End If
' Validate date
If Not dateCell.IsDateTime Then
result.DateError = "Invalid date format"
End If
results.Add(result)
Next
' Helper methods
Private Function IsValidPhoneNumber(phone As String) As Boolean
Return Regex.IsMatch(phone, "^\d{3}-\d{3}-\d{4}$")
End Function
Private Function IsValidEmail(email As String) As Boolean
Return email.Contains("@") AndAlso email.Contains(".")
End Function
如何在 Excel 試算表中加入公式?
using Formula 屬性套用 Excel 公式。 IronXL 支援標準的 Excel 公式語法。
:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-9.cs
using IronXL;
// Add formulas to calculate percentages
int lastRow = 50;
for (int row = 2; row < lastRow; row++)
{
// Calculate percentage: current value / total
workSheet[$"C{row}"].Formula = $"=B{row}/B{lastRow}";
// Format as percentage
workSheet[$"C{row}"].FormatString = "0.00%";
}
// Add summary formulas
workSheet["B52"].Formula = "=SUM(B2:B50)"; // Sum
workSheet["B53"].Formula = "=AVERAGE(B2:B50)"; // Average
workSheet["B54"].Formula = "=MAX(B2:B50)"; // Maximum
workSheet["B55"].Formula = "=MIN(B2:B50)"; // Minimum
// Force formula evaluation
workBook.EvaluateAll();
Imports IronXL
' Add formulas to calculate percentages
Dim lastRow As Integer = 50
For row As Integer = 2 To lastRow - 1
' Calculate percentage: current value / total
workSheet($"C{row}").Formula = $"=B{row}/B{lastRow}"
' Format as percentage
workSheet($"C{row}").FormatString = "0.00%"
Next
' Add summary formulas
workSheet("B52").Formula = "=SUM(B2:B50)" ' Sum
workSheet("B53").Formula = "=AVERAGE(B2:B50)" ' Average
workSheet("B54").Formula = "=MAX(B2:B50)" ' Maximum
workSheet("B55").Formula = "=MIN(B2:B50)" ' Minimum
' Force formula evaluation
workBook.EvaluateAll()
若要編輯現有公式,請參閱 Excel 公式教學。
如何驗證試算表資料?
IronXL 能為試算表提供全面性的資料驗證功能。 此範例利用外部函式庫及 C# 內建功能,對電話號碼、電子郵件和日期進行驗證。
using System.Text.RegularExpressions;
using IronXL;
// Validation implementation
for (int i = 2; i <= 101; i++)
{
var result = new PersonValidationResult { Row = i };
results.Add(result);
// Get cells for current person
var cells = workSheet[$"A{i}:E{i}"].ToList();
// Validate phone (column B)
string phone = cells[1].StringValue;
if (!Regex.IsMatch(phone, @"^\+?1?\d{10,14}$"))
{
result.PhoneNumberErrorMessage = "Invalid phone format";
}
// Validate email (column D)
string email = cells[3].StringValue;
if (!Regex.IsMatch(email, @"^[^@\s]+@[^@\s]+\.[^@\s]+$"))
{
result.EmailErrorMessage = "Invalid email address";
}
// Validate date (column E)
if (!cells[4].IsDateTime)
{
result.DateErrorMessage = "Invalid date format";
}
}
using System.Text.RegularExpressions;
using IronXL;
// Validation implementation
for (int i = 2; i <= 101; i++)
{
var result = new PersonValidationResult { Row = i };
results.Add(result);
// Get cells for current person
var cells = workSheet[$"A{i}:E{i}"].ToList();
// Validate phone (column B)
string phone = cells[1].StringValue;
if (!Regex.IsMatch(phone, @"^\+?1?\d{10,14}$"))
{
result.PhoneNumberErrorMessage = "Invalid phone format";
}
// Validate email (column D)
string email = cells[3].StringValue;
if (!Regex.IsMatch(email, @"^[^@\s]+@[^@\s]+\.[^@\s]+$"))
{
result.EmailErrorMessage = "Invalid email address";
}
// Validate date (column E)
if (!cells[4].IsDateTime)
{
result.DateErrorMessage = "Invalid date format";
}
}
Imports System.Text.RegularExpressions
Imports IronXL
' Validation implementation
For i As Integer = 2 To 101
Dim result = New PersonValidationResult With {.Row = i}
results.Add(result)
' Get cells for current person
Dim cells = workSheet($"A{i}:E{i}").ToList()
' Validate phone (column B)
Dim phone As String = cells(1).StringValue
If Not Regex.IsMatch(phone, "^\+?1?\d{10,14}$") Then
result.PhoneNumberErrorMessage = "Invalid phone format"
End If
' Validate email (column D)
Dim email As String = cells(3).StringValue
If Not Regex.IsMatch(email, "^[^@\s]+@[^@\s]+\.[^@\s]+$") Then
result.EmailErrorMessage = "Invalid email address"
End If
' Validate date (column E)
If Not cells(4).IsDateTime Then
result.DateErrorMessage = "Invalid date format"
End If
Next i
將驗證結果儲存至新工作表:
// Create results worksheet
var resultsSheet = workBook.CreateWorkSheet("ValidationResults");
// Add headers
resultsSheet["A1"].Value = "Row";
resultsSheet["B1"].Value = "Valid";
resultsSheet["C1"].Value = "Phone Error";
resultsSheet["D1"].Value = "Email Error";
resultsSheet["E1"].Value = "Date Error";
// Style headers
resultsSheet["A1:E1"].Style.Font.Bold = true;
resultsSheet["A1:E1"].Style.SetBackgroundColor("#4472C4");
resultsSheet["A1:E1"].Style.Font.Co/lor = "#FFFFFF";
// Output validation results
for (int i = 0; i < results.Co/unt; i++)
{
var result = results[i];
int outputRow = i + 2;
resultsSheet[$"A{outputRow}"].Value = result.Row;
resultsSheet[$"B{outputRow}"].Value = result.IsValid ? "Yes" : "No";
resultsSheet[$"C{outputRow}"].Value = result.PhoneNumberErrorMessage ?? "";
resultsSheet[$"D{outputRow}"].Value = result.EmailErrorMessage ?? "";
resultsSheet[$"E{outputRow}"].Value = result.DateErrorMessage ?? "";
// Highlight invalid rows
if (!result.IsValid)
{
resultsSheet[$"A{outputRow}:E{outputRow}"].Style.SetBackgroundColor("#FFE6E6");
}
}
// Auto-fit columns
for (int col = 0; col < 5; col++)
{
resultsSheet.AutoSizeColumn(col);
}
// Save validated workbook
workBook.SaveAs(@"Spreadsheets\PeopleValidated.xlsx");
// Create results worksheet
var resultsSheet = workBook.CreateWorkSheet("ValidationResults");
// Add headers
resultsSheet["A1"].Value = "Row";
resultsSheet["B1"].Value = "Valid";
resultsSheet["C1"].Value = "Phone Error";
resultsSheet["D1"].Value = "Email Error";
resultsSheet["E1"].Value = "Date Error";
// Style headers
resultsSheet["A1:E1"].Style.Font.Bold = true;
resultsSheet["A1:E1"].Style.SetBackgroundColor("#4472C4");
resultsSheet["A1:E1"].Style.Font.Co/lor = "#FFFFFF";
// Output validation results
for (int i = 0; i < results.Co/unt; i++)
{
var result = results[i];
int outputRow = i + 2;
resultsSheet[$"A{outputRow}"].Value = result.Row;
resultsSheet[$"B{outputRow}"].Value = result.IsValid ? "Yes" : "No";
resultsSheet[$"C{outputRow}"].Value = result.PhoneNumberErrorMessage ?? "";
resultsSheet[$"D{outputRow}"].Value = result.EmailErrorMessage ?? "";
resultsSheet[$"E{outputRow}"].Value = result.DateErrorMessage ?? "";
// Highlight invalid rows
if (!result.IsValid)
{
resultsSheet[$"A{outputRow}:E{outputRow}"].Style.SetBackgroundColor("#FFE6E6");
}
}
// Auto-fit columns
for (int col = 0; col < 5; col++)
{
resultsSheet.AutoSizeColumn(col);
}
// Save validated workbook
workBook.SaveAs(@"Spreadsheets\PeopleValidated.xlsx");
Imports System
' Create results worksheet
Dim resultsSheet = workBook.CreateWorkSheet("ValidationResults")
' Add headers
resultsSheet("A1").Value = "Row"
resultsSheet("B1").Value = "Valid"
resultsSheet("C1").Value = "Phone Error"
resultsSheet("D1").Value = "Email Error"
resultsSheet("E1").Value = "Date Error"
' Style headers
resultsSheet("A1:E1").Style.Font.Bold = True
resultsSheet("A1:E1").Style.SetBackgroundColor("#4472C4")
resultsSheet("A1:E1").Style.Font.Color = "#FFFFFF"
' Output validation results
For i As Integer = 0 To results.Count - 1
Dim result = results(i)
Dim outputRow As Integer = i + 2
resultsSheet($"A{outputRow}").Value = result.Row
resultsSheet($"B{outputRow}").Value = If(result.IsValid, "Yes", "No")
resultsSheet($"C{outputRow}").Value = If(result.PhoneNumberErrorMessage, "")
resultsSheet($"D{outputRow}").Value = If(result.EmailErrorMessage, "")
resultsSheet($"E{outputRow}").Value = If(result.DateErrorMessage, "")
' Highlight invalid rows
If Not result.IsValid Then
resultsSheet($"A{outputRow}:E{outputRow}").Style.SetBackgroundColor("#FFE6E6")
End If
Next
' Auto-fit columns
For col As Integer = 0 To 4
resultsSheet.AutoSizeColumn(col)
Next
' Save validated workbook
workBook.SaveAs("Spreadsheets\PeopleValidated.xlsx")
如何將 Excel 資料匯出至資料庫?
搭配 Entity Framework 使用 IronXL,可將試算表資料直接匯出至資料庫。 此範例展示如何將各國 GDP 資料匯出至 SQLite。
using System;
using System.Com/ponentModel.DataAnnotations;
using Microsoft.EntityFrameworkCore;
using IronXL;
// Define entity model
public class Country
{
[Key]
public Guid Id { get; set; } = Guid.NewGuid();
[Required]
[MaxLength(100)]
public string Name { get; set; }
[Range(0, double.MaxValue)]
public decimal GDP { get; set; }
public DateTime ImportedDate { get; set; } = DateTime.UtcNow;
}
using System;
using System.Com/ponentModel.DataAnnotations;
using Microsoft.EntityFrameworkCore;
using IronXL;
// Define entity model
public class Country
{
[Key]
public Guid Id { get; set; } = Guid.NewGuid();
[Required]
[MaxLength(100)]
public string Name { get; set; }
[Range(0, double.MaxValue)]
public decimal GDP { get; set; }
public DateTime ImportedDate { get; set; } = DateTime.UtcNow;
}
Imports System
Imports System.ComponentModel.DataAnnotations
Imports Microsoft.EntityFrameworkCore
Imports IronXL
' Define entity model
Public Class Country
<Key>
Public Property Id As Guid = Guid.NewGuid()
<Required>
<MaxLength(100)>
Public Property Name As String
<Range(0, Double.MaxValue)>
Public Property GDP As Decimal
Public Property ImportedDate As DateTime = DateTime.UtcNow
End Class
設定 Entity Framework 上下文以執行資料庫操作:
public class CountryContext : DbContext
{
public DbSet<Country> Countries { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
// Configure SQLite connection
optionsBuilder.UseSqlite("Data Source=CountryGDP.db");
// Enable sensitive data logging in development
#if DEBUG
optionsBuilder.EnableSensitiveDataLogging();
#endif
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// Configure decimal precision
modelBuilder.Entity<Country>()
.Property(c => c.GDP)
.HasPrecision(18, 2);
}
}
public class CountryContext : DbContext
{
public DbSet<Country> Countries { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
// Configure SQLite connection
optionsBuilder.UseSqlite("Data Source=CountryGDP.db");
// Enable sensitive data logging in development
#if DEBUG
optionsBuilder.EnableSensitiveDataLogging();
#endif
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// Configure decimal precision
modelBuilder.Entity<Country>()
.Property(c => c.GDP)
.HasPrecision(18, 2);
}
}
Public Class CountryContext
Inherits DbContext
Public Property Countries() As DbSet(Of Country)
Protected Overrides Sub OnConfiguring(ByVal optionsBuilder As DbContextOptionsBuilder)
' Configure SQLite connection
optionsBuilder.UseSqlite("Data Source=CountryGDP.db")
' Enable sensitive data logging in development
#If DEBUG Then
optionsBuilder.EnableSensitiveDataLogging()
#End If
End Sub
Protected Overrides Sub OnModelCreating(ByVal modelBuilder As ModelBuilder)
' Configure decimal precision
modelBuilder.Entity(Of Country)().Property(Function(c) c.GDP).HasPrecision(18, 2)
End Sub
End Class
Microsoft.EntityFrameworkCore.SqlServer 適用於 SQL Server),並據此修改連線設定。將 Excel 資料匯入資料庫:
using System.Threading.Tasks;
using IronXL;
using Microsoft.EntityFrameworkCore;
public async Task ImportGDPDataAsync()
{
try
{
// Load Excel file
var workBook = WorkBook.Load(@"Spreadsheets\GDP.xlsx");
var workSheet = workBook.GetWorkSheet("GDPByCountry");
using (var context = new CountryContext())
{
// Ensure database exists
await context.Database.EnsureCreatedAsync();
// Clear existing data (optional)
await context.Database.ExecuteSqlRawAsync("DELETE FROM Countries");
// Import data with progress tracking
int totalRows = 213;
for (int row = 2; row <= totalRows; row++)
{
// Read country data
var countryName = workSheet[$"A{row}"].StringValue;
var gdpValue = workSheet[$"B{row}"].DecimalValue;
// Skip empty rows
if (string.IsNullOrWhiteSpace(countryName))
continue;
// Create and add entity
var country = new Country
{
Name = countryName.Trim(),
GDP = gdpValue * 1_000_000 // Convert to actual value if in millions
};
await context.Co/untries.AddAsync(country);
// Save in batches for performance
if (row % 50 == 0)
{
await context.SaveChangesAsync();
Console.WriteLine($"Imported {row - 1} of {totalRows} countries");
}
}
// Save remaining records
await context.SaveChangesAsync();
Console.WriteLine($"Successfully imported {await context.Co/untries.CountAsync()} countries");
}
}
catch (Exception ex)
{
Console.WriteLine($"Import failed: {ex.Message}");
throw;
}
}
using System.Threading.Tasks;
using IronXL;
using Microsoft.EntityFrameworkCore;
public async Task ImportGDPDataAsync()
{
try
{
// Load Excel file
var workBook = WorkBook.Load(@"Spreadsheets\GDP.xlsx");
var workSheet = workBook.GetWorkSheet("GDPByCountry");
using (var context = new CountryContext())
{
// Ensure database exists
await context.Database.EnsureCreatedAsync();
// Clear existing data (optional)
await context.Database.ExecuteSqlRawAsync("DELETE FROM Countries");
// Import data with progress tracking
int totalRows = 213;
for (int row = 2; row <= totalRows; row++)
{
// Read country data
var countryName = workSheet[$"A{row}"].StringValue;
var gdpValue = workSheet[$"B{row}"].DecimalValue;
// Skip empty rows
if (string.IsNullOrWhiteSpace(countryName))
continue;
// Create and add entity
var country = new Country
{
Name = countryName.Trim(),
GDP = gdpValue * 1_000_000 // Convert to actual value if in millions
};
await context.Co/untries.AddAsync(country);
// Save in batches for performance
if (row % 50 == 0)
{
await context.SaveChangesAsync();
Console.WriteLine($"Imported {row - 1} of {totalRows} countries");
}
}
// Save remaining records
await context.SaveChangesAsync();
Console.WriteLine($"Successfully imported {await context.Co/untries.CountAsync()} countries");
}
}
catch (Exception ex)
{
Console.WriteLine($"Import failed: {ex.Message}");
throw;
}
}
Imports System.Threading.Tasks
Imports IronXL
Imports Microsoft.EntityFrameworkCore
Public Async Function ImportGDPDataAsync() As Task
Try
' Load Excel file
Dim workBook = WorkBook.Load("Spreadsheets\GDP.xlsx")
Dim workSheet = workBook.GetWorkSheet("GDPByCountry")
Using context As New CountryContext()
' Ensure database exists
Await context.Database.EnsureCreatedAsync()
' Clear existing data (optional)
Await context.Database.ExecuteSqlRawAsync("DELETE FROM Countries")
' Import data with progress tracking
Dim totalRows As Integer = 213
For row As Integer = 2 To totalRows
' Read country data
Dim countryName = workSheet($"A{row}").StringValue
Dim gdpValue = workSheet($"B{row}").DecimalValue
' Skip empty rows
If String.IsNullOrWhiteSpace(countryName) Then
Continue For
End If
' Create and add entity
Dim country As New Country With {
.Name = countryName.Trim(),
.GDP = gdpValue * 1_000_000 ' Convert to actual value if in millions
}
Await context.Countries.AddAsync(country)
' Save in batches for performance
If row Mod 50 = 0 Then
Await context.SaveChangesAsync()
Console.WriteLine($"Imported {row - 1} of {totalRows} countries")
End If
Next
' Save remaining records
Await context.SaveChangesAsync()
Console.WriteLine($"Successfully imported {Await context.Countries.CountAsync()} countries")
End Using
Catch ex As Exception
Console.WriteLine($"Import failed: {ex.Message}")
Throw
End Try
End Function
如何將 API 資料匯入 Excel 試算表?
將 IronXL 與 HTTP 客戶端結合使用,即可將即時 API 資料填入試算表中。 此範例使用 RestClient.Net 來擷取國家資料。
using System;
using System.Co/llections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;
using IronXL;
// Define data model matching API response
public class RestCountry
{
public string Name { get; set; }
public long Population { get; set; }
public string Region { get; set; }
public string NumericCode { get; set; }
public List<Language> Languages { get; set; }
}
public class Language
{
public string Name { get; set; }
public string NativeName { get; set; }
}
// Fetch and process API data
public async Task ImportCountryDataAsync()
{
using var httpClient = new HttpClient();
try
{
// Call REST API
var response = await httpClient.GetStringAsync("https://restcountries.com/v3.1/all");
var countries = JsonConvert.DeserializeObject<List<RestCountry>>(response);
// Create new workbook
var workBook = WorkBook.Create(ExcelFileFormat.XLSX);
var workSheet = workBook.CreateWorkSheet("Countries");
// Add headers with styling
string[] headers = { "Country", "Population", "Region", "Code", "Language 1", "Language 2", "Language 3" };
for (int col = 0; col < headers.Length; col++)
{
var headerCell = workSheet[0, col];
headerCell.Value = headers[col];
headerCell.Style.Font.Bold = true;
headerCell.Style.SetBackgroundColor("#366092");
headerCell.Style.Font.Co/lor = "#FFFFFF";
}
// Import country data
await ProcessCountryData(countries, workSheet);
// Save workbook
workBook.SaveAs("CountriesFromAPI.xlsx");
}
catch (Exception ex)
{
Console.WriteLine($"API import failed: {ex.Message}");
}
}
using System;
using System.Co/llections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;
using IronXL;
// Define data model matching API response
public class RestCountry
{
public string Name { get; set; }
public long Population { get; set; }
public string Region { get; set; }
public string NumericCode { get; set; }
public List<Language> Languages { get; set; }
}
public class Language
{
public string Name { get; set; }
public string NativeName { get; set; }
}
// Fetch and process API data
public async Task ImportCountryDataAsync()
{
using var httpClient = new HttpClient();
try
{
// Call REST API
var response = await httpClient.GetStringAsync("https://restcountries.com/v3.1/all");
var countries = JsonConvert.DeserializeObject<List<RestCountry>>(response);
// Create new workbook
var workBook = WorkBook.Create(ExcelFileFormat.XLSX);
var workSheet = workBook.CreateWorkSheet("Countries");
// Add headers with styling
string[] headers = { "Country", "Population", "Region", "Code", "Language 1", "Language 2", "Language 3" };
for (int col = 0; col < headers.Length; col++)
{
var headerCell = workSheet[0, col];
headerCell.Value = headers[col];
headerCell.Style.Font.Bold = true;
headerCell.Style.SetBackgroundColor("#366092");
headerCell.Style.Font.Co/lor = "#FFFFFF";
}
// Import country data
await ProcessCountryData(countries, workSheet);
// Save workbook
workBook.SaveAs("CountriesFromAPI.xlsx");
}
catch (Exception ex)
{
Console.WriteLine($"API import failed: {ex.Message}");
}
}
Imports System
Imports System.Collections.Generic
Imports System.Net.Http
Imports System.Threading.Tasks
Imports Newtonsoft.Json
Imports IronXL
' Define data model matching API response
Public Class RestCountry
Public Property Name As String
Public Property Population As Long
Public Property Region As String
Public Property NumericCode As String
Public Property Languages As List(Of Language)
End Class
Public Class Language
Public Property Name As String
Public Property NativeName As String
End Class
' Fetch and process API data
Public Async Function ImportCountryDataAsync() As Task
Using httpClient As New HttpClient()
Try
' Call REST API
Dim response As String = Await httpClient.GetStringAsync("https://restcountries.com/v3.1/all")
Dim countries As List(Of RestCountry) = JsonConvert.DeserializeObject(Of List(Of RestCountry))(response)
' Create new workbook
Dim workBook As WorkBook = WorkBook.Create(ExcelFileFormat.XLSX)
Dim workSheet As WorkSheet = workBook.CreateWorkSheet("Countries")
' Add headers with styling
Dim headers As String() = {"Country", "Population", "Region", "Code", "Language 1", "Language 2", "Language 3"}
For col As Integer = 0 To headers.Length - 1
Dim headerCell = workSheet(0, col)
headerCell.Value = headers(col)
headerCell.Style.Font.Bold = True
headerCell.Style.SetBackgroundColor("#366092")
headerCell.Style.Font.Color = "#FFFFFF"
Next
' Import country data
Await ProcessCountryData(countries, workSheet)
' Save workbook
workBook.SaveAs("CountriesFromAPI.xlsx")
Catch ex As Exception
Console.WriteLine($"API import failed: {ex.Message}")
End Try
End Using
End Function
API 會以以下格式傳回 JSON 資料:
來自 REST 國家 API 的 JSON 回應範例,顯示分層的國家資訊。
處理並將 API 資料寫入 Excel:
private async Task ProcessCountryData(List<RestCountry> countries, WorkSheet workSheet)
{
for (int i = 0; i < countries.Co/unt; i++)
{
var country = countries[i];
int row = i + 1; // Start from row 1 (after headers)
// Write basic country data
workSheet[$"A{row}"].Value = country.Name;
workSheet[$"B{row}"].Value = country.Population;
workSheet[$"C{row}"].Value = country.Region;
workSheet[$"D{row}"].Value = country.NumericCode;
// Format population with thousands separator
workSheet[$"B{row}"].FormatString = "#,##0";
// Add up to 3 languages
for (int langIndex = 0; langIndex < Math.Min(3, country.Languages?.Count ?? 0); langIndex++)
{
var language = country.Languages[langIndex];
string columnLetter = ((char)('E' + langIndex)).ToString();
workSheet[$"{columnLetter}{row}"].Value = language.Name;
}
// Add conditional formatting for regions
if (country.Region == "Europe")
{
workSheet[$"C{row}"].Style.SetBackgroundColor("#E6F3FF");
}
else if (country.Region == "Asia")
{
workSheet[$"C{row}"].Style.SetBackgroundColor("#FFF2E6");
}
// Show progress every 50 countries
if (i % 50 == 0)
{
Console.WriteLine($"Processed {i} of {countries.Co/unt} countries");
}
}
// Auto-size all columns
for (int col = 0; col < 7; col++)
{
workSheet.AutoSizeColumn(col);
}
}
private async Task ProcessCountryData(List<RestCountry> countries, WorkSheet workSheet)
{
for (int i = 0; i < countries.Co/unt; i++)
{
var country = countries[i];
int row = i + 1; // Start from row 1 (after headers)
// Write basic country data
workSheet[$"A{row}"].Value = country.Name;
workSheet[$"B{row}"].Value = country.Population;
workSheet[$"C{row}"].Value = country.Region;
workSheet[$"D{row}"].Value = country.NumericCode;
// Format population with thousands separator
workSheet[$"B{row}"].FormatString = "#,##0";
// Add up to 3 languages
for (int langIndex = 0; langIndex < Math.Min(3, country.Languages?.Count ?? 0); langIndex++)
{
var language = country.Languages[langIndex];
string columnLetter = ((char)('E' + langIndex)).ToString();
workSheet[$"{columnLetter}{row}"].Value = language.Name;
}
// Add conditional formatting for regions
if (country.Region == "Europe")
{
workSheet[$"C{row}"].Style.SetBackgroundColor("#E6F3FF");
}
else if (country.Region == "Asia")
{
workSheet[$"C{row}"].Style.SetBackgroundColor("#FFF2E6");
}
// Show progress every 50 countries
if (i % 50 == 0)
{
Console.WriteLine($"Processed {i} of {countries.Co/unt} countries");
}
}
// Auto-size all columns
for (int col = 0; col < 7; col++)
{
workSheet.AutoSizeColumn(col);
}
}
Imports System
Imports System.Threading.Tasks
Private Async Function ProcessCountryData(countries As List(Of RestCountry), workSheet As WorkSheet) As Task
For i As Integer = 0 To countries.Count - 1
Dim country = countries(i)
Dim row As Integer = i + 1 ' Start from row 1 (after headers)
' Write basic country data
workSheet($"A{row}").Value = country.Name
workSheet($"B{row}").Value = country.Population
workSheet($"C{row}").Value = country.Region
workSheet($"D{row}").Value = country.NumericCode
' Format population with thousands separator
workSheet($"B{row}").FormatString = "#,##0"
' Add up to 3 languages
For langIndex As Integer = 0 To Math.Min(3, If(country.Languages?.Count, 0)) - 1
Dim language = country.Languages(langIndex)
Dim columnLetter As String = ChrW(AscW("E"c) + langIndex).ToString()
workSheet($"{columnLetter}{row}").Value = language.Name
Next
' Add conditional formatting for regions
If country.Region = "Europe" Then
workSheet($"C{row}").Style.SetBackgroundColor("#E6F3FF")
ElseIf country.Region = "Asia" Then
workSheet($"C{row}").Style.SetBackgroundColor("#FFF2E6")
End If
' Show progress every 50 countries
If i Mod 50 = 0 Then
Console.WriteLine($"Processed {i} of {countries.Count} countries")
End If
Next
' Auto-size all columns
For col As Integer = 0 To 6
workSheet.AutoSizeColumn(col)
Next
End Function
物件參考與資源
請參閱詳盡的 IronXL API 參考手冊,以獲取詳細的類別文件及進階功能說明。
Excel 操作的額外教學:
摘要
IronXl.Excel 是一個全面的 .NET 函式庫,用於讀取和處理各種格式的 Excel 檔案。 本工具可獨立運作,無需安裝 Microsoft Excel 或 Interop。
若需進行基於雲端的試算表操作,您亦可探索 Google Sheets API Client Library for .NET,該工具可與 IronXL for .NET 的本地檔案處理功能相輔相成。
常見問題
如何在不使用 Microsoft Office 的情況下,透過 C# 讀取 Excel 檔案?
您可以使用 IronXL 在 C# 中讀取 Excel 檔案,無需 Microsoft Office。IronXL 提供諸如 WorkBook.Load() 來開啟 Excel 檔案,並讓您透過直覺的語法存取及操作資料。
using C# 可以讀取哪些格式的 Excel 檔案?
透過 IronXL,您可以在 C# 中讀取 XLS 和 XLSX 兩種檔案格式。IronXL程式庫會自動偵測檔案格式,並透過 WorkBook.Load() 方法進行相應處理。
如何在 C# 中驗證 Excel 資料?
IronXL 讓您能夠透過 C# 程式碼,藉由遍歷儲存格並套用邏輯(例如電子郵件的正規表達式或自訂驗證函式),來驗證 Excel 資料。您可以使用 CreateWorkSheet().
如何使用 C# 將 Excel 中的資料匯出至 SQL 資料庫?
若要將資料從 Excel 匯出至 SQL 資料庫,請使用 IronXL 讀取 Excel 資料,並搭配 WorkBook.Load() 和 GetWorkSheet() 方法讀取 Excel 資料,接著透過 Entity Framework 遍歷儲存格,將資料傳輸至您的資料庫。
我能否將 Excel 功能整合到 .NET Core 應用程式中?
是的,IronXL 支援與 ASP.NET Core 應用程式的整合。您可以使用 WorkBook 和 WorkSheet 類別來處理 Excel 檔案上傳、生成報表等操作。
是否可以使用 C# 在 Excel 試算表中加入公式?
IronXL 讓您能夠透過程式設計方式在 Excel 試算表中加入公式。您可以使用 Formula 屬性設定公式,例如 cell.Formula = "=SUM(A1:A10)" 並透過 workBook.EvaluateAll().
如何將 REST API 的資料填入 Excel 檔案中?
若要將 REST API 的資料填入 Excel 檔案,請搭配 HTTP 客戶端使用 IronXL 擷取 API 資料,然後透過 sheet["A1"].Value。IronXL 會自動處理 Excel 的格式與結構。
在生產環境中使用 Excel 函式庫有哪些授權選項?
IronXL 提供免費試用版供開發用途,而正式授權價格自 749 美元起。這些授權包含專屬技術支援,並允許在各種環境中部署,無需額外的 Office 授權。

