IronXL 教程 如何在 C# 中讀取 Excel 文件 How to Read Excel Files in C# Without Interop: Complete Developer Guide Jacob Mellor 更新日期:8月 17, 2025 Download IronXL NuGet 下載 DLL 下載 Start Free Trial Copy for LLMs Copy for LLMs Copy page as Markdown for LLMs Open in ChatGPT Ask ChatGPT about this page Open in Gemini Ask Gemini about this page Open in Grok Ask Grok about this page Open in Perplexity Ask Perplexity about this page Share Share on Facebook Share on X (Twitter) Share on LinkedIn Copy URL Email article This article was translated from English: Does it need improvement? Translated View the article in English 使用 IronXL 掌握在 C# 中操縱 Excel 文件的技術,這個強大的 .NET 庫不需要安裝 Microsoft Office 即可讀取、驗證和導出電子表格數據。 這個綜合教程演示了包括數據驗證、數據庫轉換和 REST API 集成在內的實用 Excel 操作。 快速開始:用 IronXL 在一行中讀取一個單元格 只需一行,您便可加載一個 Excel 工作簿並使用 IronXL 檢索單元格的值。 它被設計得易於使用—無需 Interop,無需複雜設定—只需快速訪問數據。 Get started making PDFs with NuGet now: Install IronXL with NuGet Package Manager PM > Install-Package IronXL.Excel Copy and run this code snippet. var value = IronXL.WorkBook.Load("file.xlsx").GetWorkSheet(0)["A1"].StringValue; Deploy to test on your live environment Start using IronXL in your project today with a free trial Free 30 day Trial 如何設置 IronXL 來讀取 C# 的 Excel 文件? 在您的 C# 專案中設置 IronXL 以讀取 Excel 文件僅需幾分鐘。 該庫支持 .XLS 和 .XLSX 格式,適用於各種與 Excel 相關的任務。 按照以下步驟開始使用: 下載用於讀取 Excel 文件的 C# 庫 使用 WorkBook.Load() 加載和讀取 Excel 工作簿 使用 GetWorkSheet() 方法訪問工作表 使用直觀的語法讀取單元格值,例如 sheet["A1"].Value 以編程方式驗證和處理電子表格數據 使用 Entity Framework 將數據導出到數據庫 IronXL 擅長在 C# 中讀寫 Microsoft Excel 文件。 該庫獨立運行—它既不需要 Microsoft Excel,也不需要 Interop 功能。 事實上,IronXL 提供比 Microsoft.Office.Interop.Excel 更快速、更直觀的 API。 IronXL 包括: 來自 .NET 工程師的專門產品支持 通過 Microsoft Visual Studio 輕松安裝 免費試用測試以供開發。 許可證從 $liteLicense 起 使用 IronXL 軟件庫,在 C# 和 VB.NET 中讀取和創建 Excel 文件變得簡單明瞭。 使用 IronXL 讀取 .XLS 和 .XLSX Excel 文件 以下是使用 IronXL 讀取 Excel 文件的基本工作流程: Install the IronXL Excel Library via NuGet package or download the .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}"); IRON VB CONVERTER ERROR developers@ironsoftware.com $vbLabelText $csharpLabel 此代碼演示了幾個關鍵 IronXL 功能:加載工作簿,按地址訪問單元格,遍歷範圍並執行計算。 WorkBook.Load() 方法智能地檢測文件格式,而範圍語法 ["A2:A10"] 提供類 Excel 的單元格選擇。 LINQ 集成使得在單元格集合上進行強大的數據查詢和聚合成為可能。 本教程中的代碼示例使用三個示例 Excel 電子表格,展示不同的數據場景: 教程中使用的示例 Excel 文件(GDP.xlsx、People.xlsx 和 PopulationByState.xlsx)顯示各種 IronXL 操作。 如何安裝 IronXL C# 庫? 立即開始在您的項目中使用 IronXL 並免費試用。 第一步: 免費啟動 安裝 IronXL.Excel 庫為您的 .NET 框架項目添加全面的 Excel 功能。 您可以選擇 NuGet 安裝或手動 DLL 集成。 安裝 IronXL NuGet 包 在 Visual Studio 中,右鍵單擊您的項目並選擇“管理 NuGet 程序包...” 在瀏覽標籤中搜索“IronXL.Excel” 點擊安裝按鈕將 IronXL 添加到您的項目中 通過 Visual Studio 的 NuGet 包管理器安裝 IronXL 提供自動依賴管理。 或者,使用包管理器控制台安裝 IronXL: 打開包管理器控制台(工具 → NuGet 包管理器 → 包管理器控制台) 運行安裝命令: Install-Package IronXL.Excel 您也可以在NuGet 網站上查看包詳情。 手動安裝 如需手動安裝,下載 IronXL .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"); IRON VB CONVERTER ERROR developers@ironsoftware.com $vbLabelText $csharpLabel 每個 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}"); } IRON VB CONVERTER ERROR developers@ironsoftware.com $vbLabelText $csharpLabel 如何在 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") $vbLabelText $csharpLabel 注意:僅在需要與 Excel 2003 及更早版本的兼容性時使用 ExcelFileFormat.XLS。 如何可以將工作表添加到 Excel 文檔中? 一個 IronXL WorkBook 包含一系列的工作表。 了解這種結構有助於構建多表 Excel 文件。 IronXL 中的工作簿結構包含多個工作表對象的直觀表示。 使用 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; IRON VB CONVERTER ERROR developers@ironsoftware.com $vbLabelText $csharpLabel 如何讀取和編輯單元格值? 讀取和編輯單個單元格 通過工作表的索引器屬性訪問單個單元格。 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}"); } IRON VB CONVERTER ERROR developers@ironsoftware.com $vbLabelText $csharpLabel 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() $vbLabelText $csharpLabel 如何處理單元格範圍? Range 類表示一組單元格,使之能夠對 Excel 數據進行批量操作。 :path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-8.cs // 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 ' 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 $vbLabelText $csharpLabel 當已知單元格數量時,使用循環有效地處理範圍: // 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.Contains("@") && email.Contains("."); // 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.Contains("@") && email.Contains("."); ' 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 Private results = New List(Of ValidationResult)() For row As Integer = 2 To 101 Dim result = 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 row ' Helper methods 'INSTANT VB TODO TASK: Local functions are not converted by Instant VB: 'bool IsValidPhoneNumber(string phone) '{ ' Return System.Text.RegularExpressions.Regex.IsMatch(phone, "^\d{3}-\d{3}-\d{4}$"); '} 'INSTANT VB TODO TASK: Local functions are not converted by Instant VB: 'bool IsValidEmail(string email) '{ ' Return email.Contains("@") && email.Contains("."); '} $vbLabelText $csharpLabel 如何向 Excel 試算表添加公式? 使用 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(); IRON VB CONVERTER ERROR developers@ironsoftware.com $vbLabelText $csharpLabel 要編輯現有公式,請參考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 $vbLabelText $csharpLabel 將驗證結果保存到新工作表中: // 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.Color = "#FFFFFF"; // Output validation results for (int i = 0; i < results.Count; 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.Color = "#FFFFFF"; // Output validation results for (int i = 0; i < results.Count; 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 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 i ' Auto-fit columns For col As Integer = 0 To 4 resultsSheet.AutoSizeColumn(col) Next col ' Save validated workbook workBook.SaveAs("Spreadsheets\PeopleValidated.xlsx") $vbLabelText $csharpLabel 如何將 Excel 數據導出到數據庫? 將 IronXL 與 Entity Framework 結合使用,可以將電子表格數據直接導出到數據庫。 此示例演示了將國家 GDP 數據導出到 SQLite。 using System; using System.ComponentModel.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.ComponentModel.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 $vbLabelText $csharpLabel 為數據庫操作配置 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 $vbLabelText $csharpLabel 請注意注意:要使用不同的數據庫,請安裝適當的 NuGet 包(例如,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.Countries.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.Countries.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.Countries.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.Countries.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 = 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 Dim row As Integer = 2 Do While row <= totalRows ' Read country data Dim countryName = workSheet($"A{row}").StringValue Dim gdpValue = workSheet($"B{row}").DecimalValue ' Skip empty rows If String.IsNullOrWhiteSpace(countryName) Then row += 1 Continue Do End If ' Create and add entity Dim country As New Country With { .Name = countryName.Trim(), .GDP = gdpValue * 1_000_000 } 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 row += 1 Loop ' 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 $vbLabelText $csharpLabel 如何導入 API 數據到 Excel 試算表中? 將 IronXL 與 HTTP 客戶端結合,可將 API 實時數據填入試算表。 此示例使用 RestClient.Net 拉取國家數據。 using System; using System.Collections.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.Color = "#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.Collections.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.Color = "#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 Dim httpClient As New HttpClient() Try ' Call REST API Dim response = Await httpClient.GetStringAsync("https://restcountries.com/v3.1/all") Dim countries = JsonConvert.DeserializeObject(Of List(Of RestCountry))(response) ' Create new workbook Dim workBook = WorkBook.Create(ExcelFileFormat.XLSX) Dim 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 col ' 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 Function $vbLabelText $csharpLabel API 返回如此格式的 JSON 數據: 來自 REST Countries API 的示例 JSON 響應,顯示分層結構的國家信息。 處理並將 API 數據寫入 Excel: private async Task ProcessCountryData(List<RestCountry> countries, WorkSheet workSheet) { for (int i = 0; i < countries.Count; 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.Count} 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.Count; 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.Count} countries"); } } // Auto-size all columns for (int col = 0; col < 7; col++) { workSheet.AutoSizeColumn(col); } } Private Async Function ProcessCountryData(ByVal countries As List(Of RestCountry), ByVal 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 langIndex ' 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 i ' Auto-size all columns For col As Integer = 0 To 6 workSheet.AutoSizeColumn(col) Next col End Function $vbLabelText $csharpLabel 對象參考和資源 瀏覽全面的 IronXL API 參考,以獲取詳細的類文檔和高級功能。 其他 Excel 操作教程: 以編程方式創建 Excel 文件 Excel 格式化和樣式指南 使用 Excel 公式 Excel 圖表創建教程 總結 IronXL.Excel 是一個用於讀取和操作各種格式 Excel 文件的綜合 .NET 庫。 它獨立運行,無需Microsoft Excel 或 Interop 安裝。 對於基於雲的試算表操作,您還可探索 .NET 的 Google Sheets API 客戶端庫,這是對 IronXL 本地文件能力的補充。 準備在您的C#項目中實現 Excel 自動化? Download IronXL or explore 許可選項以便生產使用。 常見問題解答 如何在 C# 中讀取 Excel 文件而不使用 Microsoft Office? 您可以使用 IronXL 在 C# 中讀取 Excel 文件,無需 Microsoft Office。IronXL 提供像 WorkBook.Load() 這樣的方法來打開 Excel 文件,並允許您使用直觀的語法訪問和操作數據。 可以使用 C# 讀取哪些格式的 Excel 文件? 使用 IronXL,您可以在 C# 中讀取 XLS 和 XLSX 文件格式。該庫自動檢測文件格式,並使用 WorkBook.Load() 方法相應地處理。 如何在 C# 中驗證 Excel 數據? IronXL 允許您在 C# 中以程式方式驗證 Excel 數據,通過迭代單元格並應用邏輯,如電子郵件正則表達式或自定義驗證函數。您可以使用 CreateWorkSheet() 生成報告。 如何使用 C# 將 Excel 數據導出到 SQL 數據庫? 要將 Excel 數據導出到 SQL 數據庫,使用 IronXL 讀取 Excel 數據配合 WorkBook.Load() 和 GetWorkSheet() 方法,然後遍歷單元格以通過 Entity Framework 將數據轉移到數據庫。 是否可以將 Excel 功能集成到 ASP.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 文件,使用 IronXL 配合 HTTP 客戶端獲取 API 數據,然後使用 sheet["A1"].Value 等方法將其寫入 Excel。IronXL 管理 Excel 的格式和結構。 在生產環境中使用 Excel 庫的授權選項有哪些? IronXL 提供用於開發目的的免費試用版,而生產許可證從 $749 起。這些許可證包含專業技術支持,且允許在各種環境中部署,而無需額外的 Office 許可證。 Jacob Mellor 立即與工程團隊聊天 首席技术官 Jacob Mellor 是 Iron Software 的首席技術官,作為 C# PDF 技術的先鋒工程師。作為 Iron Software 核心代碼的原作者,他自開始以來塑造了公司產品架構,與 CEO Cameron Rimington 一起將其轉變為一家擁有超過 50 名員工的公司,為 NASA、特斯拉 和 全世界政府機構服務。Jacob 持有曼徹斯特大學土木工程一級榮譽学士工程學位(BEng) (1998-2001)。他於 1999 年在倫敦開設了他的第一家軟件公司,並於 2005 年製作了他的首個 .NET 組件,專注於解決 Microsoft 生態系統內的複雜問題。他的旗艦產品 IronPDF & IronSuite .NET 庫在全球 NuGet 被安裝超過 3000 萬次,其基礎代碼繼續為世界各地的開發工具提供動力。擁有 25 年的商業經驗和 41 年的編碼專業知識,Jacob 仍專注於推動企業級 C#、Java 及 Python PDF 技術的創新,同時指導新一代技術領袖。 準備好開始了嗎? Nuget 下載 1,686,155 | 版本: 2025.11 剛剛發布 免費 NuGet 下載 總下載量:1,686,155 查看許可證