Jak otworzyć pliki Excel w C#
IronXL enables C# developers to open, read, and manipulate Excel files without requiring Microsoft Office installation. Simply load workbooks using WorkBook.Load(), access worksheets, and read cell values with intuitive syntax like sheet["A1"].
This tutorial explores using IronXL to open and read Excel files in C# projects, providing junior developers with comprehensive examples and best practices for working with Excel data.
What is IronXL Excel Library?
IronXL is a .NET library that prioritizes ease of use, accuracy, and speed. It helps you open, read, create, and edit Excel files efficiently without requiring MS Office Interop, making it a practical choice for developers seeking to work with Excel in C# without Interop.
IronXL is compatible with all .NET Frameworks along with Linux, macOS, Docker, Azure, and AWS. You can use it to create Console, Web, and Desktop Applications such as Blazor and .NET MAUI for modern Web Apps. It supports different workbook formats like XLS and XLSX files, XSLT and XLSM, CSV, and TSV.
What Are the Key Features of IronXL?
- Open, read, and search data in XLS/XLSX/CSV/TSV formats using LoadSpreadsheets.
- Export Excel Worksheets to multiple formats with Save & Export.
- Encrypt and decrypt files with passwords using secure features.
- Work with Excel sheets as
DataSetandDataTableobjects through DataSet integration. - Excel formulas recalculate automatically, supporting Math Functions.
- Edit spreadsheet data with intuitive range syntax like
WorkSheet["A1:B10"]. - Sort Cell Ranges, Columns, and Rows.
- Style Cells with Font, Background, Border, Alignment, and Number formats.
How to Open an Excel File in C#?
What Do I Need Before Starting?
To use IronXL in C# applications, install the following components on your local computer:
- Visual Studio - The official IDE for developing C# .NET applications. Program Visual Studio można pobrać i zainstalować ze strony internetowej firmy Microsoft. You can also use
JetBrainsReSharper& Rider. For additional setup guidance, refer to the Get Started Overview. - IronXL - The Excel library that helps work with Excel sheets in C#. Przed użyciem należy zainstalować go w aplikacji C#. You can download it from the NuGet website or from Manage NuGet packages in Visual Studio. You can also download the .NET Excel DLL file directly. For licensing implementation, see Using License Keys.
Which Namespaces Should I Import?
Once Visual Studio and IronXL are installed, add the necessary IronXL namespaces by including the following line at the top of your C# file:
// Add reference to the IronXL library
using IronXL;
// Add reference to the IronXL library
using IronXL;
' Add reference to the IronXL library
Imports IronXL
For working with specific Excel formats or advanced features, you might also need:
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
How Do I Load an Existing Excel File?
Excel files, also known as workbooks, consist of multiple worksheets, each containing cell values. To open and read an Excel file, load it using the WorkBook class's Load method. The LoadSpreadsheets functionality supports various formats.
// 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
This initializes the workbook as a WorkBook instance. To open a specific WorkSheet, retrieve it from the WorkSheets collection. The Manage Worksheet guide provides more details on worksheet operations:
// 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
This accesses the first sheet in the Excel file, ready for reading and writing.
Excel File
How Do I Read Data from Excel Cells?
Once the Excel file is opened, it's ready for reading data. Reading data from Excel files in C# using IronXL is straightforward. You can read cell values by specifying the cell reference using the Select Range functionality.
The following code retrieves the value of a cell:
// 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
Oto wynik:
Read Excel
To read data from a range of cells, use a loop to iterate through the specified range. The Select Excel Range example provides more patterns:
// 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
Each value in the cell range A2:A6 is accessed and printed to the console.
Read Range of Cells
For more detailed reading and writing examples, check the Excel reading tutorial in C#. You can also convert Excel data to DataTables for easier manipulation:
// 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
How Can I Create a New Excel File?
IronXL ułatwia również tworzenie nowych skoroszytów do zapisywania i pobierania danych. Przewodnik "Tworzenie arkuszy kalkulacyjnych" zawiera obszerne przykłady.
Możesz utworzyć nowy plik Excel za pomocą jednej linii kodu:
// 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"
Następnie utwórz arkusz roboczy i dodaj do niego dane. Aby uzyskać informacje na temat bardziej zaawansowanych wzorców tworzenia, zobacz sekcję Tworzenie nowego pliku Excel.
Jak dodać arkusze do skoroszytu?
// 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")
Ten kod dodaje do skoroszytu arkusz o nazwie "GDPByCountry", umożliwiający dodawanie wartości do komórek. Dowiedz się więcej o zarządzaniu arkuszami i kopiowaniu arkuszy.
Aby ustawić wartość dla konkretnej komórki, użyj poniższego kodu:
// 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")
Ostateczny wynik to:
Dodaj wartość do komórki
Praca z różnymi formatami plików Excel
IronXL obsługuje wiele formatów Excel. Oto jak postępować z różnymi typami plików:
// 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
Dowiedz się więcej o konwersji typów plików arkuszy kalkulacyjnych oraz konwersji plików XLSX do formatów CSV, JSON i XML.
Obsługa błędów i najlepsze praktyki
Podczas pracy z plikami Excel należy zapewnić odpowiednią obsługę błędów:
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
W przypadku aplikacji produkcyjnych warto rozważyć skonfigurowanie logowania i wdrożenie odpowiednich wzorców obsługi błędów.
Czego się nauczyliśmy?
W tym artykułe pokazano, jak otwierać i odczytywać pliki Excel, takie jak XLS i XLSX, w języku C# przy użyciu biblioteki IronXL. IronXL nie wymaga instalacji programu Microsoft Excel w systemie do wykonywania zadań związanych z Excelem, dzięki czemu idealnie nadaje się do wdrożeń w Dockerze i funkcji Azure.
IronXL zapewnia kompleksowe rozwiązanie do programowego wykonywania zadań związanych z programem Excel, w tym obliczania formuł, sortowania ciągów znaków, przycinania, wyszukiwania i zamiany, scałania i rozdzielania, zapisywania plików i wielu innych. Można również ustawić formaty danych w komórkach, korzystać z formatowania warunkówego oraz tworzyć wykresy.
Aby poznać zaawansowane funkcje, zapoznaj się z grupowaniem i rozgrupowywaniem, nazwanymi zakresami, hiperłączami oraz zabezpieczaniem plików Excel. Pełna dokumentacja API zawiera szczegółowe informacje na temat wszystkich funkcji.
IronXL jest dostępny w ramach bezpłatnego 30-dniowego okresu próbnego i można uzyskać licencję na jego komercyjne wykorzystanie. IronXL's Lite package starts from $799. Aby uzyskać dodatkowe zasoby, odwiedź sekcję samouczków lub zapoznaj się z przykładami kodu dla typowych scenariuszy.
Często Zadawane Pytania
Jak mogę otwierać pliki Excel w C# bez użycia Interop?
Możesz otwierać pliki Excel w C# bez użycia Interop, korzystając z biblioteki IronXL. Użyj metody WorkBook.Load, aby załadować plik Excel do instancji WorkBook, co pozwoli Ci uzyskać dostęp do danych w pliku i manipulować nimi.
Jakie formaty plików są kompatybilne z tą biblioteką C# dla programu Excel?
IronXL obsługuje różne formaty plików Excel, w tym XLS, XLSX, CSV i TSV. Dzięki temu programiści mogą elastycznie otwierać, odczytywać i zapisywać te formaty w swoich aplikacjach napisanych w języku C#.
Czy za pomocą tej biblioteki mogę edytować pliki Excel w języku C#?
Tak, za pomocą IronXL można edytować pliki Excel. Po załadowaniu skoroszytu można modyfikować dane, dodawać nowe arkusze, a następnie zapisywać zmiany z powrotem do pliku lub eksportować go w różnych formatach.
Jak zainstalować tę bibliotekę, aby używać jej w moim projekcie C#?
Aby zainstalować IronXL w projekcie C#, można użyć menedżera pakietów NuGet w Visual Studio w celu dodania biblioteki. Alternatywnie można pobrać bibliotekę DLL .NET Excel i odwołać się do niej w projekcie.
Czy za pomocą tej biblioteki można szyfrować pliki Excel?
Tak, IronXL umożliwia szyfrowanie i deszyfrowanie plików Excel. Możesz zabezpieczyć swoje dokumenty Excel hasłami, aby chronić poufne dane podczas operacji na plikach.
Czy ta biblioteka obsługuje ponowne obliczanie formuł w arkuszach Excel?
IronXL obsługuje automatyczne przeliczanie formuł, zapewniając, że wszelkie zmiany w danych automatycznie aktualizują formuły, tak jak w programie Excel.
Jak mogę odczytać konkretne wartości komórek w arkuszu Excel przy użyciu tej biblioteki?
Aby odczytać konkretne wartości komórek za pomocą IronXL, można odwołać się do komórki przy użyciu notacji programu Excel. Na przykład sheet["A1"].StringValue pobierze wartość ciągu znaków z komórki A1.
Czy z tej biblioteki można korzystać w różnych systemach operacyjnych?
Tak, IronXL jest kompatybilny z wieloma systemami operacyjnymi, w tym Windows, Linux i macOS. Obsługuje również wdrażanie w środowiskach Docker, Azure i AWS.
Jakie są zalety korzystania z tej biblioteki w porównaniu z MS Office Interop?
IronXL oferuje kilka zalet w porównaniu z MS Office Interop, takich jak brak konieczności instalowania programu Excel w systemie, lepsza wydajność w środowiskach serwerowych oraz łatwość użytkowania z nowoczesnymi aplikacjami .NET.
Czy dostępna jest bezpłatna wersja próbna tej biblioteki C# dla programu Excel?
Tak, IronXL oferuje 30-dniowy bezpłatny okres probny, który pozwala przetestować jego funkcje i możliwości przed podjęciem decyzji o zakupie licencji komercyjnej do swoich projektów.




