如何在 C# 中讀取 Excel 文件

How to Read Excel Files in C# Without Interop: Complete Developer Guide

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

使用IronXL掌握 C# 中的 Excel 檔案操作-IronXL 是一個強大的.NET函式庫,無需安裝 Microsoft Office 即可讀取、驗證和匯出電子表格資料。 本教學課程全面示範了 Excel 的實用操作,包括資料驗證、資料庫轉換和 REST API 整合。

快速入門:使用IronXL一行讀取細胞

使用IronXL,只需一行程式碼即可載入 Excel 工作簿並擷取儲存格的值。 它的設計宗旨是方便易用——無需互操作,無需複雜設定——只需快速存取您的資料。

  1. 使用NuGet套件管理器安裝https://www.nuget.org/packages/IronXl.Excel

    PM > Install-Package IronXl.Excel
  2. 複製並運行這段程式碼。

    var value = IronXl.WorkBook.Load("file.xlsx").GetWorkSheet(0)["A1"].StringValue;
  3. 部署到您的生產環境進行測試

    今天就在您的專案中開始使用免費試用IronXL

    arrow pointer

如何在 C# 中設定IronXL以讀取 Excel 檔案?

在 C# 專案中設定IronXL以讀取 Excel 檔案只需幾分鐘。 本函式庫同時支援 .XLS.XLSX 格式,使其能夠勝任任何與 Excel 相關的任務。

請依照以下步驟開始:

1.下載用於讀取 Excel 檔案的 C# 函式庫

  1. 使用 WorkBook.Load() 載入並讀取 Excel 工作簿
  2. 使用 GetWorkSheet() 方法存取工作表
  3. 使用類似 sheet["A1"].Value 的直覺式語法讀取儲存格值
  4. 以程式方式驗證和處理電子表格數據
  5. 使用 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 檔案的基本工作流程:

  1. 透過NuGet套件安裝IronXL Excel 函式庫,或下載.NET Excel DLL檔。
  2. 使用 WorkBook.Load() 方法讀取任何 XLS、XLSX 或 CSV 文檔
  3. 使用直覺的語法存取儲存格值:sheet["A11"].DecimalValue
:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-1.cs
using IronXL;
using System;
using System.Linq;

// 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}");
$vbLabelText   $csharpLabel

這段程式碼示範了IronXL 的幾個關鍵功能:載入工作簿、按地址存取儲存格、遍歷範圍以及執行計算。 WorkBook.Load() 方法可以智慧地偵測檔案格式,而範圍語法 ["A2:A10"] 則提供了類似 Excel 的儲存格選擇。 LINQ 整合支援對單元格集合進行強大的資料查詢和聚合。

本教學中的程式碼範例使用三個範例 Excel 電子表格,分別展示了不同的資料場景:

Visual Studio 解決方案資源管理器中顯示的三個 Excel 電子表格檔案 本教學中用於示範各種IronXL操作的範例 Excel 檔案(GDP.xlsx、People.xlsx 和 PopulationByState.xlsx)。


如何安裝IronXL C# 函式庫?


安裝 IronXl.Excel 函式庫,即可為您的.NET Framework專案新增全面的 Excel 功能。 選擇NuGet安裝或手動 DLL 整合。

安裝IronXL NuGet套件

  1. 在 Visual Studio 中,右鍵點選您的項目,然後選擇"管理NuGet套件..."
  2. 在"瀏覽"標籤中搜尋"IronXl.Excel"。
  3. 點選"安裝"按鈕,將IronXL新增到您的專案中。

 NuGet套件管理器介面顯示IronXl.Excel 套件的安裝 透過 Visual Studio 的NuGet套件管理器安裝IronXL可實現自動相依性管理。

或者,使用軟體套件管理器控制台安裝IronXL :

  1. 開啟套件管理員控制台(工具 → NuGet套件管理器 → 套件管理員控制台)
  2. 運行安裝命令:
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");
$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}");
}
$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");
$vbLabelText   $csharpLabel

注意:僅在需要與 Excel 2003 及更早版本相容時才使用 ExcelFileFormat.XLS

如何在Excel文件中新增工作表?

IronXL WorkBook 包含一系列工作紙。 了解這種結構有助於建立多工作表 Excel 檔案。

顯示包含多個工作表的 Workbook 的圖表 IronXL中包含多個 WorkSheet 物件的 WorkBook 結構的視覺化表示。

使用 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;
$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}");
}
$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();
$vbLabelText   $csharpLabel

如何使用單元格區域?

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
$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(".");
$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();
$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";
    }
}
$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");
$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;
}
$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);
    }
}
$vbLabelText   $csharpLabel

請注意注意:若要使用不同的資料庫,請安裝對應的NuGet套件(例如,SQL Server 的 Microsoft.EntityFrameworkCore.SqlServer),並相應地修改連線配置。

將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;
    }
}
$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}");
    }
}
$vbLabelText   $csharpLabel

API 傳回的 JSON 資料格式如下:

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);
    }
}
$vbLabelText   $csharpLabel

物件參考和資源

查閱全面的IronXL API 參考文檔,以了解詳細的類文檔和高級功能。

更多Excel操作教學:

-透過程式設計方式建立 Excel 文件 Excel格式和樣式指南 -使用Excel公式

概括

IronXl.Excel 是一個全面的.NET函式庫,用於讀取和操作各種格式的 Excel 檔案。 它無需安裝Microsoft Excel或 Interop 即可獨立運行。

對於基於雲端的電子表格操作,您還可以探索適用於.NET的Google Sheets API 用戶端程式庫,它補充了 IronXL 的本機檔案功能。

準備好在 C# 專案中實現 Excel 自動化了嗎? 下載IronXL或了解適用於生產環境的授權選項

常見問題解答

如何在 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 應用程序集成。您可以在控制器中使用 WorkBookWorkSheet 類來處理 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, Team Iron 首席技術官
首席技術官

Jacob Mellor是Iron Software的首席技術官,也是開創C# PDF技術的前瞻性工程師。作為Iron Software核心代碼庫的原始開發者,他自公司成立以來就塑造了公司的產品架構,並與CEO Cameron Rimington將公司轉型為服務NASA、Tesla以及全球政府機構的50多人公司。

Jacob擁有曼徹斯特大學土木工程一級榮譽學士學位(1998年–2001年)。他於1999年在倫敦開立首家軟體公司,並於2005年建立了他的第一個.NET組件,專注於解決Microsoft生態系統中的複雜問題。

他的旗艦作品IronPDF和Iron Suite .NET程式庫全球已獲得超過3000萬次NuGet安裝,他的基礎代碼不斷在全球各地驅動開發者工具。擁有25年以上的商業經驗和41年的編碼專業知識,Jacob仍然專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

A PHP Error was encountered

Severity: Notice

Message: Undefined index: IronXl.Excel

Filename: helpers/counter_helper.php

Line Number: 85

Backtrace:

File: /var/www/ironpdf.com/application/helpers/counter_helper.php
Line: 85
Function: _error_handler

File: /var/www/ironpdf.com/application/views/main/sections/ready_to_started_202509.php
Line: 12
Function: getTotalDonwloadNumber

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 489
Function: view

File: /var/www/ironpdf.com/application/controllers/Products/Tutorials.php
Line: 29
Function: render_products_view

File: /var/www/ironpdf.com/index.php
Line: 292
Function: require_once

A PHP Error was encountered

Severity: Notice

Message: Undefined index: IronXl.Excel

Filename: helpers/counter_helper.php

Line Number: 85

Backtrace:

File: /var/www/ironpdf.com/application/helpers/counter_helper.php
Line: 85
Function: _error_handler

File: /var/www/ironpdf.com/application/views/main/sections/ready_to_started_202509.php
Line: 19
Function: getTotalDonwloadNumber

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 489
Function: view

File: /var/www/ironpdf.com/application/controllers/Products/Tutorials.php
Line: 29
Function: render_products_view

File: /var/www/ironpdf.com/index.php
Line: 292
Function: require_once

準備好開始了嗎?
Nuget 下載 1,890,100 | 版本: 2026.3 剛剛發布

A PHP Error was encountered

Severity: Notice

Message: Undefined index: IronXl.Excel

Filename: helpers/counter_helper.php

Line Number: 85

Backtrace:

File: /var/www/ironpdf.com/application/helpers/counter_helper.php
Line: 85
Function: _error_handler

File: /var/www/ironpdf.com/application/views/main/sections/still_scrolling_202512.php
Line: 17
Function: getTotalDonwloadNumber

File: /var/www/ironpdf.com/application/views/products/sections/three_column_docs_page_structure.php
Line: 71
Function: view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 88
Function: view

File: /var/www/ironpdf.com/application/views/products/tutorials/index.php
Line: 2
Function: view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 88
Function: view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 552
Function: view

File: /var/www/ironpdf.com/application/controllers/Products/Tutorials.php
Line: 29
Function: render_products_view

File: /var/www/ironpdf.com/index.php
Line: 292
Function: require_once

A PHP Error was encountered

Severity: Notice

Message: Undefined index: IronXl.Excel

Filename: helpers/counter_helper.php

Line Number: 85

Backtrace:

File: /var/www/ironpdf.com/application/helpers/counter_helper.php
Line: 85
Function: _error_handler

File: /var/www/ironpdf.com/application/views/main/sections/still_scrolling_202512.php
Line: 24
Function: getTotalDonwloadNumber

File: /var/www/ironpdf.com/application/views/products/sections/three_column_docs_page_structure.php
Line: 71
Function: view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 88
Function: view

File: /var/www/ironpdf.com/application/views/products/tutorials/index.php
Line: 2
Function: view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 88
Function: view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 552
Function: view

File: /var/www/ironpdf.com/application/controllers/Products/Tutorials.php
Line: 29
Function: render_products_view

File: /var/www/ironpdf.com/index.php
Line: 292
Function: require_once

Still Scrolling Icon

還在捲動嗎?

想要快速證明? PM > Install-Package IronXl.Excel
執行範例 觀看您的資料變成試算表。