如何在 C# 中開啟 Excel 文件
IronXL使C#開發者能夠打開、讀取和操作Excel文件,而無需安裝Microsoft Office。 只需使用sheet["A1"]的直觀語法讀取單元格值。
本教程探討使用IronXL在C#項目中打開和讀取Excel文件,為初級開發者提供全面的範例和最佳做法使用Excel資料。
什麼是IronXL Excel程式庫?
IronXL是一個.NET程式庫,重點在於易用性、準確性和速度。 它幫助您高效地打開、讀取、建立和編輯Excel文件,無需MS Office Interop,對於尋求在C#中使用Excel但不使用Interop的開發者來說,是一個實用的選擇。
IronXL is compatible with all .NET Frameworks along with Linux, macOS, Docker, Azure, and AWS. 您可以使用它來建立Console、Web和Desktop應用程式,如Blazor和.NET MAUI,用於現代Web應用程式。它支持多種工作簿格式,如XLS和XLSX文件、XSLT和XLSM、CSV和TSV。
IronXL的關鍵功能有哪些?
如何在C#中打開Excel文件?
在開始之前我需要什麼?
要在C#應用程式中使用IronXL,請在您的計算機上安裝以下組件:
- Visual Studio - 開發C# .NET應用程式的官方IDE。 您可以從Microsoft網站下載並安裝Visual Studio。 您還可以使用
JetBrainsReSharper和Rider。 有關其他設置指導,請參閱開始概覽。 - IronXL - 使用C#處理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;
' Add reference to the IronXL library
Imports IronXL
要使用特定Excel格式或高級功能,您可能還需要:
using IronXL.Formatting; // For cell styling
using IronXL.Drawing; // For images and charts
using System.Data; // For DataSet/DataTable operations
using IronXL.Formatting; // For cell styling
using IronXL.Drawing; // For images and charts
using System.Data; // For DataSet/DataTable operations
Imports IronXL.Formatting ' For cell styling
Imports IronXL.Drawing ' For images and charts
Imports 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);
// }
' Supported Excel spreadsheet formats for reading include: XLSX, XLS, CSV, and TSV
Dim workbook As WorkBook = WorkBook.Load("test.xlsx")
' You can also load from streams for web applications
' Using stream = File.OpenRead("test.xlsx")
' Dim workbook As WorkBook = WorkBook.Load(stream)
' End Using
這會將工作簿初始化為WorkBook實例。 要打開特定的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
' Access the first worksheet in the workbook
Dim sheet As WorkSheet = workbook.WorkSheets.First()
' Alternative ways to access worksheets
Dim sheetByIndex As WorkSheet = workbook.WorkSheets(0) ' By index
Dim sheetByName As WorkSheet = workbook.GetWorkSheet("Sheet1") ' By name
這將存取Excel文件中的第一個工作表,準備好進行讀寫。
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}");
}
' Select the cell using Excel notation and retrieve its integer value
Dim cellValue As Integer = sheet("C2").IntValue
' You can also retrieve values in different formats
Dim textValue As String = sheet("C2").StringValue
Dim decimalValue As Decimal = sheet("C2").DecimalValue
Dim dateValue As DateTime = sheet("C2").DateTimeValue
Dim boolValue As Boolean = sheet("C2").BoolValue
' Display the value in the console
Console.WriteLine($"Cell C2 contains: {cellValue}")
' Check if cell is empty before reading
If Not sheet("C2").IsEmpty Then
Console.WriteLine($"Cell value: {sheet("C2").Value}")
End If
輸出如以下所示:
讀取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}");
}
' Iterate through a range of cells and display their address and text content
For Each cell In sheet("A2:A6")
Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text)
Next
' Read an entire column
For Each cell In sheet.GetColumn(0) ' Column A
If Not cell.IsEmpty Then
Console.WriteLine($"Column A value: {cell.Text}")
End If
Next
' Read an entire row
For Each cell In sheet.GetRow(1) ' Row 2
Console.WriteLine($"Row 2 value: {cell.Text}")
Next
從單元格範圍A2:A6存取並列印每個值到控制台。
讀取一系列單元格
欲了解更詳細的讀取和寫入範例,請查看C#中的Excel讀取教程。 您還可以將Excel資料轉換為DataTables以便更輕鬆地操作:
// 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"]}");
}
' Convert worksheet to DataTable for easier data manipulation
Dim dataTable As DataTable = sheet.ToDataTable(True) ' True = first row contains headers
' Access data using DataTable methods
For Each row As DataRow In dataTable.Rows
Console.WriteLine($"Employee: {row("Name")}, Salary: {row("Salary")}")
Next
如何建立新的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";
' Create a new workbook with the XLSX format
Dim workBook As New WorkBook(ExcelFileFormat.XLSX)
' Alternative: Create with XLS format for compatibility
Dim xlsWorkBook As 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");
' Create a worksheet named "GDPByCountry" in the workbook
Dim workSheet As WorkSheet = workBook.CreateWorkSheet("GDPByCountry")
' Create multiple worksheets at once
Dim sheet2 As WorkSheet = workBook.CreateWorkSheet("PopulationData")
Dim sheet3 As WorkSheet = workBook.CreateWorkSheet("Summary")
' Copy an existing worksheet
Dim copiedSheet As WorkSheet = 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");
' 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.99D ' 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格式
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
' Convert between formats
Dim workbook As 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
了解轉換電子表格文件型別和將XLSX轉換為CSV、JSON、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}");
}
Imports System
Try
Dim workbook As WorkBook = WorkBook.Load("test.xlsx")
Dim sheet As WorkSheet = workbook.GetWorkSheet("Sheet1")
' Check if sheet exists
If sheet Is Nothing Then
Console.WriteLine("Worksheet not found!")
Return
End If
' Process data
Dim value = sheet("A1").Value
Catch ex As Exception
Console.WriteLine($"Error reading Excel file: {ex.Message}")
End Try
我們學到了什麼?
本文演示如何使用IronXL在C#中打開和讀取Excel文件,如XLS和XLSX。 IronXL不需要系統中安裝Microsoft Excel就能執行Excel相關任務,對於Docker部署和Azure函式非常適合。
IronXL為Excel相關任務程式化地提供了全面的解決方案,包括公式計算、字串排序、修剪、查找和替換、合併和拆分、保存文件,等等。 您還可以設置單元格資料格式、使用條件格式化,並建立圖表。
對於高級功能,探索分組和取消分組、命名範圍、超連結及保護Excel文件。 完整API 參考提供了所有功能的詳細文件。
IronXL提供免費30天試用,可用於商業用途授權。 IronXL的Lite包從$999開始。 有關其他資源,請存取教程部分,或探索程式碼範例以了解常見情境。
常見問題
我如何在 C# 中不使用 Interop 開啟 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 表格中的公式重新計算嗎?
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 天免費試用,允許您在決定購買商業授權前先測試其功能和能力。




