
如何在不使用 Microsoft Office 的情況下用 C# 開啟 Excel 文件
IronXL 讓您可以在未安裝Microsoft Office的情況下,使用C#開啟和讀取Excel文件──只需安裝NuGet套件、用WorkBook.Load("file.xlsx")載入工作簿,並使用型別值和自動格式檢測存取任何工作表、單元格或範圍。
如果您曾經嘗試在沒有Microsoft Office的情況下以程式方式開啟Excel文件,您會知道傳統的Interop方法有多棘手。 Interop依賴於安裝Excel本身,需要複雜的COM參考,並且經常導致版本衝突──特別是在Office不可用的伺服器或雲環境中。
IronXL 是一個現代的.NET程式庫,可讓您直接讀取XLSX、XLS、CSV和TSV文件,無需任何Office依賴。 您可以撰寫乾淨、可靠的C#程式碼,在Windows、Linux或雲端處理Excel文件,並跳過所有COM自動化的摩擦。 本指南從安裝到適用於開啟和讀取Excel工作簿的生產就緒模式進行了全程說明。
如何在.NET專案中安裝IronXL?
開始只需幾秒鐘。 打開您的專案並使用以下其中一個套件管理器:
或者,打開Visual Studio,右鍵點擊您的專案,選擇"管理NuGet套件",搜索"IronXL",然後點擊安裝。 安裝指南涵蓋所有支援的環境,包括Docker和Azure。

一旦安裝完成,在文件頂部新增namespace:
using IronXL;Imports IronXL這單行就是您所需的全部。 沒有複雜的COM參考,沒有Office依賴,也沒有版本專屬的組件。 如需免費評估金鑰,請存取IronXL試用授權頁面。
IronXL 為何比傳統Interop更簡單?
傳統的Excel Interop要求每台運行您程式的機器上都有Microsoft Office。 這對於伺服器部署、AWS Lambda函式和容器化應用程式而言是不可行的。 IronXL在內部處理所有Excel文件解析,提供一個沒有任何外部依賴的乾淨API。
使用Interop,您還需要小心管理COM物件的生命週期以防止記憶體洩漏──每個Worksheet物件必須顯式釋放,否則Excel進程會在背景中積累。 IronXL 使用標準的 .NET 垃圾收集,因此您不需要考慮COM清理。
該庫支援 .NET Framework 4.6.2 及以上版本,以及 .NET 5、6、7、8 和 10。它可以在 Windows、macOS 和 Linux 上運行而無需修改。 如果您針對的是跨平台場景,這點本身就使IronXL比僅限於Windows的Office Interop更具優勢。
如何確認安裝是否成功?
安裝後,通過載入任何Excel文件並列印單元格值來建立一個簡單的測試。 如果專案構建無錯誤且輸出與預期資料匹配,則設置完成。 IronXL文件中包含一步一步的快速入門部份,詳細介紹了此驗證步驟。
設置過程中常見的錯誤是忘記在生產中載入工作簿之前應用授權金鑰。 在試用模式下,該庫會在生成的任何文件上新增小水印。 在應用程式啟動時設置IronXL.License.LicenseKey以便所有操作從頭到尾都在正確的授權下運行。
如何打開Excel工作簿並讀取單元格值?
核心API非常簡單。 載入工作簿,選擇工作表,並通過地址或迭代存取單元格。
using IronXL;
// Load any Excel file -- XLSX, XLS, CSV, or TSV
WorkBook workbook = WorkBook.Load("example.xlsx");
// Access the second worksheet (zero-indexed)
WorkSheet worksheet = workbook.WorkSheets[1];
// Read a specific cell value
decimal revenue = worksheet["E2"].DecimalValue;
Console.WriteLine($"Order Total: {revenue}");
// Iterate over a range of cells
foreach (var cell in worksheet["C2:C6"])
{
Console.WriteLine($"Product: {cell.Text}");
}Imports IronXL
' Load any Excel file -- XLSX, XLS, CSV, or TSV
Dim workbook As WorkBook = WorkBook.Load("example.xlsx")
' Access the second worksheet (zero-indexed)
Dim worksheet As WorkSheet = workbook.WorkSheets(1)
' Read a specific cell value
Dim revenue As Decimal = worksheet("E2").DecimalValue
Console.WriteLine($"Order Total: {revenue}")
' Iterate over a range of cells
For Each cell In worksheet("C2:C6")
Console.WriteLine($"Product: {cell.Text}")
NextWorkBook.Load()自動檢測文件格式──無需指定文件是XLS或XLSX。 使用workbook.GetWorkSheet("Sheet1")按索引或名稱存取工作表。 每個單元格提供型別化的屬性,如Text。
如需開啟文件的更多選項,請參閱開啟工作簿指南。

如何按名稱存取工作表?
使用工作表名稱比數字索引更具可維護性,尤其是當其他人編輯工作簿時。 以下範例展示瞭如何按名稱查找工作表並遍歷所有工作表:
using IronXL;
WorkBook workbook = WorkBook.Load("inventory.xlsx");
// Access worksheet by exact name
WorkSheet salesSheet = workbook.GetWorkSheet("Sales Data");
Console.WriteLine($"Sales sheet rows: {salesSheet.RowCount}");
// Iterate all worksheets in the workbook
foreach (WorkSheet sheet in workbook.WorkSheets)
{
if (sheet.Name.Contains("Inventory"))
{
Console.WriteLine($"Found inventory sheet: {sheet.Name}");
}
}Imports IronXL
Dim workbook As WorkBook = WorkBook.Load("inventory.xlsx")
' Access worksheet by exact name
Dim salesSheet As WorkSheet = workbook.GetWorkSheet("Sales Data")
Console.WriteLine($"Sales sheet rows: {salesSheet.RowCount}")
' Iterate all worksheets in the workbook
For Each sheet As WorkSheet In workbook.WorkSheets
If sheet.Name.Contains("Inventory") Then
Console.WriteLine($"Found inventory sheet: {sheet.Name}")
End If
Next讀取 Excel 文件指南解釋瞭涵蓋動態生成工作表名稱的附加存取模式。
如何從Excel單元格中讀取不同的資料型別?
IronXL 為每個常見的 Excel 資料型別提供型別化的存取器。 您可以讀取字串、整數、十進制、日期、布林值以及公式結果,而不需要任何手動解析。
using IronXL;
WorkBook wb = WorkBook.Load(@"C:\Data\Inventory.xlsx");
WorkSheet ws = wb.GetWorkSheet("Products");
// Read different data types directly
string productName = ws["A2"].StringValue;
int quantity = ws["B2"].IntValue;
decimal price = ws["C2"].DecimalValue;
DateTime updated = ws["D2"].DateTimeValue;
// Use aggregate functions on ranges for performance
decimal totalStock = ws["B2:B100"].Sum();
decimal maxPrice = ws["C2:C100"].Max();
Console.WriteLine($"Product: {productName}, Qty: {quantity}, Price: {price:C}");
Console.WriteLine($"Total stock units: {totalStock}, Highest price: {maxPrice:C}");Imports IronXL
Dim wb As WorkBook = WorkBook.Load("C:\Data\Inventory.xlsx")
Dim ws As WorkSheet = wb.GetWorkSheet("Products")
' Read different data types directly
Dim productName As String = ws("A2").StringValue
Dim quantity As Integer = ws("B2").IntValue
Dim price As Decimal = ws("C2").DecimalValue
Dim updated As DateTime = ws("D2").DateTimeValue
' Use aggregate functions on ranges for performance
Dim totalStock As Decimal = ws("B2:B100").Sum()
Dim maxPrice As Decimal = ws("C2:C100").Max()
Console.WriteLine($"Product: {productName}, Qty: {quantity}, Price: {price:C}")
Console.WriteLine($"Total stock units: {totalStock}, Highest price: {maxPrice:C}")下表總結了可用的型別存取器:
| 存取器 | 返回型別 | 註釋 |
|---|---|---|
StringValue | string | 即使是數字單元格也始終返回字串 |
IntValue | int | 截斷小數值 |
DecimalValue | decimal | 最適合財務資料 |
DoubleValue | double | 用於科學或浮點數值 |
日期時間Value | 日期時間 | 自動解析 Excel 串行日期數字 |
BoolValue | bool | 讀取 TRUE/FALSE 單元格 |
Formula | string | 返回公式文字,例如=SUM(A2:D2) |
有關讀取和寫入單元格資料的完整詳細資訊,請參閱單元格格式指南和導入資料指南。

如何安全地處理空或Null單元格?
空單元格在現實世界Excel文件中很常見。 在讀取型別存取器之前使用Value是否為null:
using IronXL;
WorkBook workbook = WorkBook.Load("data.xlsx");
WorkSheet ws = workbook.DefaultWorkSheet;
// Check if a cell is empty before reading
if (!ws["A1"].IsEmpty)
{
Console.WriteLine(ws["A1"].StringValue);
}
// Provide a fallback value using a null-coalescing pattern
string cellText = ws["A1"].StringValue ?? "Default Value";
// Iterate a range and skip empty cells
foreach (var cell in ws["A1:A20"])
{
if (!cell.IsEmpty)
{
Console.WriteLine(cell.Text);
}
}Imports IronXL
Dim workbook As WorkBook = WorkBook.Load("data.xlsx")
Dim ws As WorkSheet = workbook.DefaultWorkSheet
' Check if a cell is empty before reading
If Not ws("A1").IsEmpty Then
Console.WriteLine(ws("A1").StringValue)
End If
' Provide a fallback value using a null-coalescing pattern
Dim cellText As String = If(ws("A1").StringValue, "Default Value")
' Iterate a range and skip empty cells
For Each cell In ws("A1:A20")
If Not cell.IsEmpty Then
Console.WriteLine(cell.Text)
End If
Next讀取 Excel 文件說明文件涵蓋了處理稀疏資料的附加模式,包括如何檢測工作表中最後使用的行和列。
處理空單元格時的另一個考慮因素是真正空白單元格與具有空字串的單元格之間的差異。 IsEmpty 只有在單元格完全不包含值時才返回true,而StringValue 對於空白單元格和明確設置為"" 的單元格都會返回空字串。 如果您的資料具有格式化為文字但顯示為空的單元格,則檢查 IsEmpty 和 string.IsNullOrWhiteSpace(cell.StringValue) 以獲得最準確的結果。
如何構建生產就緒的Excel閱讀程式?
實際情境中的Excel閱讀程式需要文件驗證、錯誤處理、多工作表支持和可選的輸出生成。 以下範例在一個類別中演示了所有這些模式:
using IronXL;
using System.IO;
// Validate and load the file
static List<string> CheckLowStock(string filePath)
{
var lowStockItems = new List<string>();
if (!File.Exists(filePath))
{
Console.WriteLine($"File not found: {filePath}");
return lowStockItems;
}
string ext = Path.GetExtension(filePath).ToLower();
if (ext is not (".xlsx" or ".xls" or ".csv"))
{
Console.WriteLine($"Unsupported file type: {ext}");
return lowStockItems;
}
try
{
WorkBook workbook = WorkBook.Load(filePath);
foreach (WorkSheet sheet in workbook.WorkSheets)
{
Console.WriteLine($"Checking sheet: {sheet.Name}");
for (int row = 2; row <= sheet.RowCount; row++)
{
string itemName = sheet[$"A{row}"].StringValue;
int stockLevel = sheet[$"B{row}"].IntValue;
if (stockLevel < 10 && !string.IsNullOrEmpty(itemName))
{
lowStockItems.Add($"{itemName} -- {stockLevel} units ({sheet.Name})");
}
}
}
}
catch (Exception ex)
{
Console.WriteLine($"Error reading Excel file: {ex.Message}");
}
return lowStockItems;
}
// Export results to a new workbook
static void ExportReport(List<string> items, string outputPath)
{
WorkBook report = WorkBook.Create();
WorkSheet sheet = report.CreateWorkSheet("Low Stock Report");
sheet["A1"].Value = "Item Description";
sheet["B1"].Value = "Source Sheet";
sheet["A1:B1"].Style.Font.Bold = true;
sheet["A1:B1"].Style.BackgroundColor = "#4472C4";
sheet["A1:B1"].Style.Font.Color = "#FFFFFF";
int rowIndex = 2;
foreach (string item in items)
{
sheet[$"A{rowIndex}"].Value = item;
rowIndex++;
}
report.SaveAs(outputPath);
Console.WriteLine($"Report saved to: {outputPath}");
}
// Run
var lowStockItems = CheckLowStock("inventory.xlsx");
ExportReport(lowStockItems, "low-stock-report.xlsx");Imports IronXL
Imports System.IO
' Validate and load the file
Private Shared Function CheckLowStock(filePath As String) As List(Of String)
Dim lowStockItems As New List(Of String)()
If Not File.Exists(filePath) Then
Console.WriteLine($"File not found: {filePath}")
Return lowStockItems
End If
Dim ext As String = Path.GetExtension(filePath).ToLower()
If ext <> ".xlsx" AndAlso ext <> ".xls" AndAlso ext <> ".csv" Then
Console.WriteLine($"Unsupported file type: {ext}")
Return lowStockItems
End If
Try
Dim workbook As WorkBook = WorkBook.Load(filePath)
For Each sheet As WorkSheet In workbook.WorkSheets
Console.WriteLine($"Checking sheet: {sheet.Name}")
For row As Integer = 2 To sheet.RowCount
Dim itemName As String = sheet($"A{row}").StringValue
Dim stockLevel As Integer = sheet($"B{row}").IntValue
If stockLevel < 10 AndAlso Not String.IsNullOrEmpty(itemName) Then
lowStockItems.Add($"{itemName} -- {stockLevel} units ({sheet.Name})")
End If
Next
Next
Catch ex As Exception
Console.WriteLine($"Error reading Excel file: {ex.Message}")
End Try
Return lowStockItems
End Function
' Export results to a new workbook
Private Shared Sub ExportReport(items As List(Of String), outputPath As String)
Dim report As WorkBook = WorkBook.Create()
Dim sheet As WorkSheet = report.CreateWorkSheet("Low Stock Report")
sheet("A1").Value = "Item Description"
sheet("B1").Value = "Source Sheet"
sheet("A1:B1").Style.Font.Bold = True
sheet("A1:B1").Style.BackgroundColor = "#4472C4"
sheet("A1:B1").Style.Font.Color = "#FFFFFF"
Dim rowIndex As Integer = 2
For Each item As String In items
sheet($"A{rowIndex}").Value = item
rowIndex += 1
Next
report.SaveAs(outputPath)
Console.WriteLine($"Report saved to: {outputPath}")
End Sub
' Run
Dim lowStockItems As List(Of String) = CheckLowStock("inventory.xlsx")
ExportReport(lowStockItems, "low-stock-report.xlsx")本例使用頂級語句並涵蓋了完整工作流程:驗證文件路徑和擴展名、載入工作簿、遍歷所有工作表、應用業務邏輯、並將結果寫入新文件。關於編寫和保存工作簿的更多資訊,請參閱寫入Excel文件指南和導出Excel指南。
注意WorkBook.Create()建立新工作簿,而不是修改源文件。保持源文件和輸出文件單獨是良好的審計追蹤做法,並避免意外覆蓋其他Process依賴的資料。 如果您需要向現有工作簿追加資料,則使用SaveAs()到一個新路徑或者就地覆寫。
如何有效率地處理大型Excel文件?
對於有數千行的文件,聚合函式在內部操作,因而不將每個單元格實體化為單獨的物件,比手動迴圈効能更高:
using IronXL;
WorkBook workbook = WorkBook.Load("large-dataset.xlsx");
WorkSheet ws = workbook.DefaultWorkSheet;
// Fast: aggregate functions operate on the range directly
decimal total = ws["B2:B5000"].Sum();
decimal average = ws["B2:B5000"].Avg();
int count = ws["B2:B5000"].Count();
Console.WriteLine($"Total: {total:C}, Average: {average:C}, Rows: {count}");
// Export the worksheet to a DataSet for LINQ or database operations
var dataSet = workbook.ToDataSet();
Console.WriteLine($"DataSet tables: {dataSet.Tables.Count}");Imports IronXL
Dim workbook As WorkBook = WorkBook.Load("large-dataset.xlsx")
Dim ws As WorkSheet = workbook.DefaultWorkSheet
' Fast: aggregate functions operate on the range directly
Dim total As Decimal = ws("B2:B5000").Sum()
Dim average As Decimal = ws("B2:B5000").Avg()
Dim count As Integer = ws("B2:B5000").Count()
Console.WriteLine($"Total: {total:C}, Average: {average:C}, Rows: {count}")
' Export the worksheet to a DataSet for LINQ or database operations
Dim dataSet = workbook.ToDataSet()
Console.WriteLine($"DataSet tables: {dataSet.Tables.Count}")將其轉換為DataSet特別有效,當您需要在多個工作表上運行LINQ查詢或將資料載入關係資料庫時。 每個工作表都成為DataSet,使其易於與現有的資料存取程式碼配合工作。 有關完整詳細資訊,請參閱Excel 到 DataSet 指南。
如何獲得授權並部署至生產?
IronXL 是一個商業程式庫,提供免費試用讓您在開發和測試期間獲得全部功能。 對於生產部署,您需要有效的授權金鑰。 有關開發者、團隊和企業選項等授權級別的詳細資訊,請參閱 IronXL 授權頁面。
要應用授權金鑰,請在任何IronXL調用之前設置它:
IronXL.License.LicenseKey = "YOUR-LICENSE-KEY-HERE";Imports IronXL
IronXL.License.LicenseKey = "YOUR-LICENSE-KEY-HERE"IronXL功能概述總結了從讀取和寫入文件到建立圖表、應用條件格式以及使用命名範圍的所有能力。 建立Excel文件指南和合併單元格指南是撰寫新工作簿的良好起點。
有關C# Excel自動化的社群討論和問題,Microsoft Q&A論壇和Stack Overflow是很好的資源。 官方的NuGet 套件頁面提供版本歷史和下載統計。
在C#中開啟Excel文件有哪些關鍵要點?
IronXL完全集中排除了對Microsoft Office的依賴,使得在伺服器、容器和雲功能中處理Excel文件成為可能。 此API遵循簡單的模式:載入工作簿,按名稱或索引存取工作表,並使用型別存取器讀取單元格。 像Max()之類的聚合函式處理大型資料集,而不會有手動迭代的額外負擔。
程式庫支援XLSX、XLS、CSV和TSV格式,運行於 .NET 10 和所有最新的.NET版本,並實現跨平台運作。 錯誤處理很簡單,因為 IronXL 拋出標準的 .NET 異常,您可以使用熟悉的 try/catch 模式捕捉——無需解碼 COM 互操作錯誤程式碼。 要探索所有可用選項,請從IronXL文件首頁開始,或嘗試開啟工作簿指南以參考分步指南。
開始免費的IronXL試用,無需承擔任何義務,即可在自己的專案中評估這個程式庫。

Curtis Chau擁有Carleton大學的電腦科學學士學位,專精於前端開發,擁有Node.js、TypeScript、JavaScript和React的專業知識。Curtis熱衷於建立直觀且美觀的使用者介面,喜愛使用現代框架並建立結構良好、視覺吸引力的手冊。
相關文章



