IronXL 教程 如何在 C# 中读取 Excel 文件 How to Read Excel Files in C# Without Interop: Complete Developer Guide Jacob Mellor 已更新:八月 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 Master Excel file manipulation in C# using IronXL—the powerful .NET library that reads, validates, and exports spreadsheet data without requiring Microsoft Office installation. This comprehensive tutorial demonstrates practical Excel operations including data validation, database conversion, and REST API integration. Quickstart: Read a Cell with IronXL in One Line In just one line, you can load an Excel workbook and retrieve a cell’s value using IronXL. It’s designed for ease—no Interop, no complex setup—just fast access to your data. 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 How Do I Set Up IronXL to Read Excel Files in C#? Setting up IronXL for reading Excel files in your C# project takes just minutes. The library supports both .XLS and .XLSX formats, making it versatile for any Excel-related task. Follow these steps to get started: Download the C# Library to read Excel files Load and read Excel workbooks using WorkBook.Load() Access worksheets with the GetWorkSheet() method Read cell values using intuitive syntax like sheet["A1"].Value Validate and process spreadsheet data programmatically Export data to databases using Entity Framework IronXL excels at reading and editing Microsoft Excel documents with C#. The library operates independently—it neither requires Microsoft Excel nor Interop to function. In fact, IronXL provides a faster and more intuitive API than Microsoft.Office.Interop.Excel. IronXL Includes: Dedicated product support from our .NET engineers Easy installation via Microsoft Visual Studio Free trial test for development. Licenses from $liteLicense Reading and creating Excel files in C# and VB.NET becomes straightforward using the IronXL software library. Reading .XLS and .XLSX Excel Files Using IronXL Here's the essential workflow for reading Excel files using IronXL: Install the IronXL Excel Library via NuGet package or download the .NET Excel DLL Use the WorkBook.Load() method to read any XLS, XLSX, or CSV document Access cell values using intuitive syntax: 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 This code demonstrates several key IronXL features: loading workbooks, accessing cells by address, iterating through ranges, and performing calculations. The WorkBook.Load() method intelligently detects file formats, while the range syntax ["A2:A10"] provides Excel-like cell selection. LINQ integration enables powerful data queries and aggregations on cell collections. The code examples in this tutorial work with three sample Excel spreadsheets that showcase different data scenarios: Sample Excel files (GDP.xlsx, People.xlsx, and PopulationByState.xlsx) used throughout this tutorial for demonstrating various IronXL operations. How Can I Install the IronXL C# Library? 今天在您的项目中使用 IronXL,免费试用。 第一步: 免费开始 Installing the IronXL.Excel library adds comprehensive Excel functionality to your .NET framework projects. Choose between NuGet installation or manual DLL integration. Installing the IronXL NuGet Package In Visual Studio, right-click on your project and select "Manage NuGet Packages..." Search for "IronXL.Excel" in the Browse tab Click the Install button to add IronXL to your project Installing IronXL through Visual Studio's NuGet Package Manager provides automatic dependency management. Alternatively, install IronXL using the Package Manager Console: Open the Package Manager Console (Tools → NuGet Package Manager → Package Manager Console) Run the installation command: Install-Package IronXL.Excel You can also view the package details on the NuGet website. Manual Installation For manual installation, download the IronXL .NET Excel DLL and reference it directly in your Visual Studio project. How Do I Load and Read an Excel Workbook? The WorkBook class represents an entire Excel file. Load Excel files using the WorkBook.Load() method, which accepts file paths for XLS, XLSX, CSV, and TSV formats. :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 Each WorkBook contains multiple WorkSheet objects representing individual Excel sheets. Access worksheets by name using 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 How Do I Create New Excel Documents in C#? Create new Excel documents by constructing a WorkBook object with your desired file format. IronXL supports both modern XLSX and legacy XLS formats. :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 Note: Use ExcelFileFormat.XLS only when compatibility with Excel 2003 and earlier is required. How Can I Add Worksheets to an Excel Document? An IronXL WorkBook contains a collection of worksheets. Understanding this structure helps when building multi-sheet Excel files. Visual representation of the WorkBook structure containing multiple WorkSheet objects in IronXL. Create new worksheets 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; IRON VB CONVERTER ERROR developers@ironsoftware.com $vbLabelText $csharpLabel How Do I Read and Edit Cell Values? Read and Edit a Single Cell Access individual cells through the worksheet's indexer property. IronXL's Cell class provides strongly-typed value properties. :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 The Cell class offers multiple properties for different data types, automatically converting values when possible. For more cell operations, see the Cell formatting tutorial. :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 How Can I Work with Cell Ranges? The Range class represents a collection of cells, enabling bulk operations on Excel data. :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 Process ranges efficiently using loops when cell count is known: // 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 How Do I Add Formulas to Excel Spreadsheets? Apply Excel formulas using the Formula property. IronXL supports standard Excel formula syntax. :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 To edit existing formulas, explore the Excel formulas tutorial. How Can I Validate Spreadsheet Data? IronXL enables comprehensive data validation for spreadsheets. This example validates phone numbers, emails, and dates using external libraries and built-in C# functionality. 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 Save validation results to a new worksheet: // 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 How Do I Export Excel Data to a Database? Use IronXL with Entity Framework to export spreadsheet data directly to databases. This example demonstrates exporting country GDP data to 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 Configure Entity Framework context for database operations: 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 请注意Note: To use different databases, install the appropriate NuGet package (e.g., Microsoft.EntityFrameworkCore.SqlServer for SQL Server) and modify the connection configuration accordingly. Import Excel data to database: 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 How Can I Import API Data into Excel Spreadsheets? Combine IronXL with HTTP clients to populate spreadsheets with live API data. This example uses RestClient.Net to fetch country data. 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 The API returns JSON data in this format: Sample JSON response from the REST Countries API showing hierarchical country information. Process and write the API data to 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 Object Reference and Resources Explore the comprehensive IronXL API Reference for detailed class documentation and advanced features. Additional tutorials for Excel operations: Create Excel files programmatically Excel formatting and styling guide Working with Excel formulas Excel chart creation tutorial Summary IronXL.Excel is a comprehensive .NET library for reading and manipulating Excel files in various formats. It operates independently without requiring Microsoft Excel or Interop installation. For cloud-based spreadsheet manipulation, you might also explore the Google Sheets API Client Library for .NET, which complements IronXL's local file capabilities. Ready to implement Excel automation in your C# projects? Download IronXL or explore licensing options for production use. 常见问题解答 如何在不使用 Microsoft Office 的情况下用 C# 读取 Excel 文件? 您可以使用 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 通过 WorkBook.Load() 和 GetWorkSheet() 方法读取 Excel 数据,然后遍历单元格将数据传输到数据库,使用 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 核心代码库的原始开发者,自公司成立以来,他就塑造了公司的产品架构,并与首席执行官 Cameron Rimington 一起将其转变成一家公司,拥有50多人,服务于 NASA、特斯拉和全球政府机构。Jacob 拥有曼彻斯特大学 (1998-2001) 的一级荣誉土木工程学士学位。1999 年在伦敦创办了自己的第一家软件公司,并于 2005 年创建了他的第一个 .NET 组件后,他专注于解决微软生态系统中的复杂问题。他的旗舰 IronPDF 和 IronSuite .NET 库在全球已获得超过 3000 万次的 NuGet 安装,其基础代码继续为全球使用的开发者工具提供支持。拥有 25 年商业经验和 41 年编程经验的 Jacob 仍专注于推动企业级 C#、Java 和 Python PDF 技术的创新,同时指导下一代技术领导者。 准备开始了吗? Nuget 下载 1,686,155 | 版本: 2025.11 刚刚发布 免费 NuGet 下载 总下载量:1,686,155 查看许可证