如何在 C# 中開啟 Excel 文件
IronXL 讓 C# 開發人員無需安裝 Microsoft Office 即可開啟、讀取和操作 Excel 檔案。 只需使用WorkBook.Load()載入工作簿,存取工作表,並使用類似sheet["A1"]直覺式語法讀取儲存格值。
本教學探討如何在 C# 專案中使用 IronXL 開啟和讀取 Excel 文件,為初級開發人員提供處理 Excel 資料的全面範例和最佳實踐。
IronXL Excel Library是什麼?
IronXL是一個 .NET 函式庫,它優先考慮易用性、準確性和速度。 它可以幫助您有效率地開啟、讀取、建立和編輯Excel 文件,而無需 MS Office Interop,因此對於希望在 C# 中使用 Excel 而無需 Interop 的開發人員來說,這是一個實用的選擇。
IronXL 與所有 .NET Framework 以及Linux 、 macOS 、 Docker 、 Azure和AWS相容。 您可以使用它來建立控制台應用程式、Web 應用程式和桌面應用程序,例如Blazor和.NET MAUI,用於開發現代 Web 應用程式。它支援不同的工作簿格式,例如 XLS 和 XLSX 檔案、XSLT 和 XLSM、CSV 和 TSV。
IronXL的主要特色是什麼?
如何在 C# 中開啟 Excel 檔案?
開始之前我需要準備什麼?
若要在 C# 應用程式中使用 IronXL,請在本機上安裝下列元件:
- Visual Studio - 用於開發 C# .NET 應用程式的官方 IDE。 您可以從微軟網站下載並安裝 Visual Studio。 您也可以使用
JetBrainsReSharper和 Rider 。 有關更多設定指導,請參閱入門概述。 - IronXL - 幫助在 C# 中處理 Excel 表格的 Excel 庫。 必須先將其安裝到您的 C# 應用程式中才能使用。 您可以從NuGet 網站下載,也可以從 Visual Studio 中的"管理 NuGet 套件"下載。 您也可以直接下載.NET Excel DLL檔。 有關許可實施,請參閱"使用許可證密鑰" 。
我應該導入哪些命名空間?
安裝 Visual Studio 和 IronXL 後,在 C# 檔案頂部新增以下程式碼行,以新增必要的 IronXL 命名空間:
// Add reference to the IronXL library
using IronXL;// Add reference to the IronXL library
using IronXL;要使用特定的 Excel 格式或進階功能,您可能還需要:
using IronXL.Formatting; // For cell styling
using IronXL.Drawing; // For images and charts
using System.Data; // For DataSet/DataTable operationsusing IronXL.Formatting; // For cell styling
using IronXL.Drawing; // For images and charts
using System.Data; // For DataSet/DataTable operations如何載入現有的Excel檔案?
Excel 檔案(也稱為工作簿)由多個工作表組成,每個工作表都包含儲存格值。 要開啟並讀取 Excel 文件,請使用WorkBook類別的Load方法載入它。 LoadSpreadsheets功能支援多種格式。
// Supported Excel spreadsheet formats for reading include: XLSX, XLS, CSV, and TSV
WorkBook workbook = WorkBook.Load("test.xlsx");
// You can also load from streams for web applications
// using (var stream = File.OpenRead("test.xlsx"))
// {
// WorkBook workbook = WorkBook.Load(stream);
// }// Supported Excel spreadsheet formats for reading include: XLSX, XLS, CSV, and TSV
WorkBook workbook = WorkBook.Load("test.xlsx");
// You can also load from streams for web applications
// using (var stream = File.OpenRead("test.xlsx"))
// {
// WorkBook workbook = WorkBook.Load(stream);
// }這將工作簿初始化為WorkBook實例。 若要開啟特定的WorkSheet ,請從WorkSheets集合中檢索它。 《管理工作表》指南提供了有關工作表操作的更多詳細資訊:
// Access the first worksheet in the workbook
WorkSheet sheet = workbook.WorkSheets.First();
// Alternative ways to access worksheets
WorkSheet sheetByIndex = workbook.WorkSheets[0]; // By index
WorkSheet sheetByName = workbook.GetWorkSheet("Sheet1"); // By name// Access the first worksheet in the workbook
WorkSheet sheet = workbook.WorkSheets.First();
// Alternative ways to access worksheets
WorkSheet sheetByIndex = workbook.WorkSheets[0]; // By index
WorkSheet sheetByName = workbook.GetWorkSheet("Sheet1"); // By name這將存取 Excel 文件中的第一個工作表,以便進行讀取和寫入操作。
! Excel電子表格,顯示5名員工的數據,包含姓名、職稱和薪資三列,並附有格式化的表頭和儲存格邊框。 Excel 檔案
如何讀取Excel單元格中的資料?
Excel 檔案開啟後,即可讀取資料。 使用 IronXL 在 C# 中讀取 Excel 檔案中的資料非常簡單。 您可以使用"選擇範圍"功能指定儲存格參考來讀取儲存格值。
以下程式碼用於取得儲存格的值:
// Select the cell using Excel notation and retrieve its integer value
int cellValue = sheet["C2"].IntValue;
// You can also retrieve values in different formats
string textValue = sheet["C2"].StringValue;
decimal decimalValue = sheet["C2"].DecimalValue;
DateTime dateValue = sheet["C2"].DateTimeValue;
bool boolValue = sheet["C2"].BoolValue;
// Display the value in the console
Console.WriteLine($"Cell C2 contains: {cellValue}");
// Check if cell is empty before reading
if (!sheet["C2"].IsEmpty)
{
Console.WriteLine($"Cell value: {sheet["C2"].Value}");
}// Select the cell using Excel notation and retrieve its integer value
int cellValue = sheet["C2"].IntValue;
// You can also retrieve values in different formats
string textValue = sheet["C2"].StringValue;
decimal decimalValue = sheet["C2"].DecimalValue;
DateTime dateValue = sheet["C2"].DateTimeValue;
bool boolValue = sheet["C2"].BoolValue;
// Display the value in the console
Console.WriteLine($"Cell C2 contains: {cellValue}");
// Check if cell is empty before reading
if (!sheet["C2"].IsEmpty)
{
Console.WriteLine($"Cell value: {sheet["C2"].Value}");
}輸出結果如下:
! Microsoft Visual Studio 偵錯控制台視窗顯示已成功從 Excel 儲存格 C2 中提取值"100000",並附有上下文輸出訊息。 讀取 Excel
若要從一系列儲存格讀取數據,請使用循環遍歷指定的範圍。 "選擇 Excel 區域"範例提供了更多模式:
// Iterate through a range of cells and display their address and text content
foreach (var cell in sheet["A2:A6"])
{
Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text);
}
// Read an entire column
foreach (var cell in sheet.GetColumn(0)) // Column A
{
if (!cell.IsEmpty)
{
Console.WriteLine($"Column A value: {cell.Text}");
}
}
// Read an entire row
foreach (var cell in sheet.GetRow(1)) // Row 2
{
Console.WriteLine($"Row 2 value: {cell.Text}");
}// Iterate through a range of cells and display their address and text content
foreach (var cell in sheet["A2:A6"])
{
Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text);
}
// Read an entire column
foreach (var cell in sheet.GetColumn(0)) // Column A
{
if (!cell.IsEmpty)
{
Console.WriteLine($"Column A value: {cell.Text}");
}
}
// Read an entire row
foreach (var cell in sheet.GetRow(1)) // Row 2
{
Console.WriteLine($"Row 2 value: {cell.Text}");
}存取儲存格區域A2:A6中的每個值並將其列印到控制台。
有關更詳細的讀寫範例,請查看C# 中的 Excel 讀取教學。 您也可以將 Excel 資料轉換為資料表,以便更輕鬆地進行操作:
// Convert worksheet to DataTable for easier data manipulation
DataTable dataTable = sheet.ToDataTable(true); // true = first row contains headers
// Access data using DataTable methods
foreach (DataRow row in dataTable.Rows)
{
Console.WriteLine($"Employee: {row["Name"]}, Salary: {row["Salary"]}");
}// Convert worksheet to DataTable for easier data manipulation
DataTable dataTable = sheet.ToDataTable(true); // true = first row contains headers
// Access data using DataTable methods
foreach (DataRow row in dataTable.Rows)
{
Console.WriteLine($"Employee: {row["Name"]}, Salary: {row["Salary"]}");
}如何建立新的Excel檔案?
IronXL 也方便建立新的工作簿以儲存和擷取資料。 《創建電子表格》指南提供了一個全面的範例。
只需一行程式碼即可建立一個新的 Excel 檔案:
// Create a new workbook with the XLSX format
WorkBook workBook = new WorkBook(ExcelFileFormat.XLSX);
// Alternative: Create with XLS format for compatibility
WorkBook xlsWorkBook = new WorkBook(ExcelFileFormat.XLS);
// Set workbook metadata
workBook.Metadata.Title = "Employee Data";
workBook.Metadata.Author = "Your Name";
workBook.Metadata.Keywords = "employees, salary, data";// Create a new workbook with the XLSX format
WorkBook workBook = new WorkBook(ExcelFileFormat.XLSX);
// Alternative: Create with XLS format for compatibility
WorkBook xlsWorkBook = new WorkBook(ExcelFileFormat.XLS);
// Set workbook metadata
workBook.Metadata.Title = "Employee Data";
workBook.Metadata.Author = "Your Name";
workBook.Metadata.Keywords = "employees, salary, data";接下來,建立一個工作表並在其中新增資料。 如需更進階的建立模式,請參閱建立新的 Excel 檔案。
如何在工作簿中新增工作表?
// Create a worksheet named "GDPByCountry" in the workbook
WorkSheet workSheet = workBook.CreateWorkSheet("GDPByCountry");
// Create multiple worksheets at once
WorkSheet sheet2 = workBook.CreateWorkSheet("PopulationData");
WorkSheet sheet3 = workBook.CreateWorkSheet("Summary");
// Copy an existing worksheet
WorkSheet copiedSheet = workSheet.CopySheet("GDPByCountryCopy");// Create a worksheet named "GDPByCountry" in the workbook
WorkSheet workSheet = workBook.CreateWorkSheet("GDPByCountry");
// Create multiple worksheets at once
WorkSheet sheet2 = workBook.CreateWorkSheet("PopulationData");
WorkSheet sheet3 = workBook.CreateWorkSheet("Summary");
// Copy an existing worksheet
WorkSheet copiedSheet = workSheet.CopySheet("GDPByCountryCopy");這段程式碼會在工作簿中新增一個名為"GDPByCountry"的工作表,讓您可以新增儲存格值。 了解更多關於管理工作表和複製工作表的資訊。
若要為特定儲存格設定值,請使用下列程式碼:
// Set the value of cell A1 to "Example"
workSheet["A1"].Value = "Example";
// Add different types of data
workSheet["A2"].Value = 12345; // Integer
workSheet["A3"].Value = 99.99m; // Decimal
workSheet["A4"].Value = DateTime.Now; // Date
workSheet["A5"].Value = true; // Boolean
// Add formulas
workSheet["B1"].Formula = "=SUM(A2:A3)";
// Set multiple cells at once using a range
workSheet["C1:C5"].Value = "Bulk Value";
// Save the workbook
workBook.SaveAs("output.xlsx");// Set the value of cell A1 to "Example"
workSheet["A1"].Value = "Example";
// Add different types of data
workSheet["A2"].Value = 12345; // Integer
workSheet["A3"].Value = 99.99m; // Decimal
workSheet["A4"].Value = DateTime.Now; // Date
workSheet["A5"].Value = true; // Boolean
// Add formulas
workSheet["B1"].Formula = "=SUM(A2:A3)";
// Set multiple cells at once using a range
workSheet["C1:C5"].Value = "Bulk Value";
// Save the workbook
workBook.SaveAs("output.xlsx");最終輸出結果為:
! Excel 電子表格顯示儲存格 A1 中填入了使用 C# 程式以程式設計方式新增的"範例"文本,同時顯示"按國家/地區劃分的 GDP"工作表標籤,並且儲存格會高亮顯示以指示新增的值。 向單元格添加值
使用不同的Excel格式
IronXL 支援多種 Excel 格式。 以下是如何處理不同文件類型的方法:
// Convert between formats
WorkBook workbook = WorkBook.Load("data.csv");
workbook.SaveAs("data.xlsx"); // Convert CSV to XLSX
// Export to different formats
workbook.SaveAsCsv("output.csv", ";"); // CSV with semicolon delimiter
workbook.SaveAsJson("output.json"); // Export as JSON
workbook.SaveAsXml("output.xml"); // Export as XML// Convert between formats
WorkBook workbook = WorkBook.Load("data.csv");
workbook.SaveAs("data.xlsx"); // Convert CSV to XLSX
// Export to different formats
workbook.SaveAsCsv("output.csv", ";"); // CSV with semicolon delimiter
workbook.SaveAsJson("output.json"); // Export as JSON
workbook.SaveAsXml("output.xml"); // Export as XML錯誤處理和最佳實踐
處理Excel檔案時,要實作適當的錯誤處理:
try
{
WorkBook workbook = WorkBook.Load("test.xlsx");
WorkSheet sheet = workbook.GetWorkSheet("Sheet1");
// Check if sheet exists
if (sheet == null)
{
Console.WriteLine("Worksheet not found!");
return;
}
// Process data
var value = sheet["A1"].Value;
}
catch (Exception ex)
{
Console.WriteLine($"Error reading Excel file: {ex.Message}");
}try
{
WorkBook workbook = WorkBook.Load("test.xlsx");
WorkSheet sheet = workbook.GetWorkSheet("Sheet1");
// Check if sheet exists
if (sheet == null)
{
Console.WriteLine("Worksheet not found!");
return;
}
// Process data
var value = sheet["A1"].Value;
}
catch (Exception ex)
{
Console.WriteLine($"Error reading Excel file: {ex.Message}");
}我們學到了什麼?
本文示範如何使用 IronXL 在 C# 中開啟和讀取 Excel 文件,例如 XLS 和 XLSX 文件。 IronXL 不需要在系統上安裝 Microsoft Excel 即可執行與 Excel 相關的任務,因此非常適合Docker 部署和Azure 函數。
IronXL 提供了一個全面的 Excel 相關任務程式設計解決方案,包括公式計算、字串排序、修剪、尋找和取代、合併和取消合併、儲存檔案等等。 您也可以設定儲存格資料格式、使用條件格式以及 建立圖表。
若要了解進階功能,請探索分組和取消分組、命名區域、超連結以及保護 Excel 檔案。 完整的API 參考文件提供了所有功能的詳細文件。
IronXL 提供30 天免費試用,並可授權用於商業用途。 IronXL 的 Lite 套餐起價為$799 。 如需更多資源,請造訪教學課程部分或瀏覽常見場景的程式碼範例。
常見問題解答
如何在不使用 Interop 的情況下用 C# 開啟 Excel 檔案?
您可以使用 IronXL 庫在 C# 中開啟 Excel 文件,而無需使用 Interop。使用WorkBook.Load方法將 Excel 檔案載入到WorkBook實例中,即可存取和操作檔案中的資料。
這個 C# Excel 函式庫相容哪些文件格式?
IronXL 支援多種 Excel 檔案格式,包括 XLS、XLSX、CSV 和 TSV。這使得開發人員能夠在 C# 應用程式中靈活地開啟、讀取和寫入這些格式的檔案。
我可以使用此庫在 C# 中編輯 Excel 文件嗎?
是的,您可以使用 IronXL 編輯 Excel 檔案。載入工作簿後,您可以修改資料、新增新的工作表,然後將變更儲存回檔案或將其匯出為各種格式。
如何安裝這個函式庫以便在我的 C# 專案中使用?
若要在 C# 專案中安裝 IronXL,您可以使用 Visual Studio 中的 NuGet 套件管理器新增此程式庫。或者,您可以下載 .NET Excel DLL 檔案並在專案中引用它。
是否可以使用此庫加密 Excel 文件?
是的,IronXL 允許您加密和解密 Excel 檔案。您可以使用密碼保護 Excel 文檔,從而在文件操作期間保護敏感資料。
這個函式庫是否支援在Excel表格中進行公式重新計算?
IronXL 支援自動公式重新計算,確保資料的任何變更都會自動更新公式,就像 Excel 一樣。
如何使用這個函式庫讀取Excel工作表中特定儲存格的值?
若要使用 IronXL 讀取特定儲存格的值,您可以使用 Excel 格式來引用儲存格。例如, sheet["A1"].StringValue將檢索儲存格 A1 中的字串值。
這個庫可以在不同的作業系統上使用嗎?
是的,IronXL相容於多種作業系統,包括Windows、Linux和macOS。它還支援在Docker、Azure和AWS環境中部署。
與 MS Office Interop 相比,使用此程式庫有哪些優勢?
IronXL 相比 MS Office Interop 具有多項優勢,例如無需在系統上安裝 Excel,在伺服器環境中效能更佳,並且易於與現代 .NET 應用程式一起使用。
這個 C# Excel 庫有免費試用版嗎?
是的,IronXL 提供 30 天免費試用期,讓您在決定是否為您的專案購買商業許可證之前,可以測試其功能和特性。






