Przejdź do treści stopki
KORZYSTANIE Z IRONXL

Jak konwertować Excel na DataTable w C#

This blog demonstrates how to implement an Excel to DataTable conversion. This task can be done easily using IronXL, which provides a simple and efficient way to read and write Excel files in C#.

1. IronXL

IronXL is a powerful and user-friendly C# library designed to simplify the reading, writing, exporting data, and manipulation of Excel worksheets. It provides developers with a seamless way to work with Excel spreadsheets and automate tasks within their C# projects.

With IronXL, you can easily import, export, and modify data in Excel workbooks, worksheets, and cells. It supports both the older XLS format and the newer XLSX format, making it compatible with a wide range of Excel versions.

The library offers a straightforward API that enables developers to perform various operations on Excel files, such as creating new workbooks, reading and writing data to cells, applying formatting, handling formulas, and even extracting charts and images. IronXL also supports working with complex data structures like tables, ranges, and named ranges.

2. Wymagania wstępne

To work with Excel files and convert them to DataTable using IronXL in C#, there are a few prerequisites that need to be in place:

  1. Development Environment: Ensure that you have a compatible development environment set up on your machine, such as Visual Studio or any other C# IDE.
  2. IronXL Library: Download and install the IronXL library. You can obtain the library from the official IronXL website or via the NuGet Package Manager in Visual Studio. Include the IronXL namespace in your C# project to access its classes and methods.
  3. .NET Framework or .NET Core: IronXL supports both the .NET Framework and .NET Core. Ensure that you have the appropriate version installed on your machine, depending on your project requirements.

3. Creating a New Project in C

To use the IronXL library for Excel-related tasks, the initial step is to create a .NET project in Visual Studio. While any version of Visual Studio can be used, it's recommended to use the latest one.

This tutorial will use the Console Application project template to showcase how to work with IronXL.

How to Convert Excel to DataTable in C#, Figure 1: New Project Nowy projekt

Once you have selected the project type, proceed to specify a name and location for the project. Furthermore, you have the option to choose the preferred framework for the project, such as .NET Core 6.

How to Convert Excel to DataTable in C#, Figure 2: Project Configuration Konfiguracja projektu

After the solution is generated, you can access the Program.cs file, where you can input code and create/execute the application.

How to Convert Excel to DataTable in C#, Figure 3: Program.cs Program.cs

4. Instalacja IronXL

The IronXL library can be downloaded and installed in different ways. Są to:

  • Using Visual Studio NuGet Packages
  • Using the Visual Studio Command Line

4.1 Using Visual Studio NuGet Packages

To install the IronXL library with NuGet Package Manager in Visual Studio, open the NuGet Package Manager and search for IronXL in the Browse tab.

Po znalezieniu IronXL w wynikach wyszukiwania wybierz go i kontynuuj instalację. Once the installation is complete, you can use the IronXL library in your project.

The screenshot below shows how to open the NuGet Package Manager in Visual Studio.

How to Convert Excel to DataTable in C#, Figure 4: NuGet Package Manager Menedżer pakietów NuGet

IronXL w wynikach wyszukiwania:

How to Convert Excel to DataTable in C#, Figure 5: IronXL IronXL

4.2 Using the Visual Studio Command Line

Wielu programistów woli instalować pakiety za pomocą interfejsu wiersza poleceń. Aby zainstalować IronXL za pomocą wiersza poleceń, wykonaj następujące czynności:

  • Go to Tools > Menedżer pakietów NuGet > Package Manager Console in Visual Studio.
  • Wprowadź następujący wiersz w zakładce Konsola menedżera pakietów:
Install-Package IronXl.Excel

Now the package will download and install to the current project and will be ready for use.

How to Convert Excel to DataTable in C#, Figure 6: Install the IronXL package Install the IronXL package

5. Convert Excel Data to DataTable Using IronXL

Exporting Excel data from an Excel file stream to DataTable in C# can be easily implemented using IronXL. This section will discuss how you can convert Excel worksheet data to DataTable using IronXL.

First, a sample Excel file is required with the data you want to convert into a DataTable. For demonstration, a simple Excel file should be created.

How to Convert Excel to DataTable in C#, Figure 7: Sample Excel Sample Excel

Now let's look at the code samples:

using IronXL;
using System;
using System.Data;

class Program
{
    static void Main()
    {
        // Load the Excel workbook from a file
        WorkBook workBook = WorkBook.Load("sample.xlsx");

        // Access the default worksheet in the workbook
        WorkSheet workSheet = workBook.DefaultWorkSheet;

        // Convert the worksheet data to a DataTable
        // Set the parameter to true to consider the first row as column headers
        DataTable dataTable = workSheet.ToDataTable(true);

        // Iterate over each row in the DataTable
        foreach (DataRow row in dataTable.Rows)
        {
            // Print each column in the row
            for (int i = 0; i < dataTable.Columns.Count; i++)
            {
                Console.Write($"{row[i]} \t");
            }
            Console.WriteLine(); // Move to the next line after printing each row
        }
    }
}
using IronXL;
using System;
using System.Data;

class Program
{
    static void Main()
    {
        // Load the Excel workbook from a file
        WorkBook workBook = WorkBook.Load("sample.xlsx");

        // Access the default worksheet in the workbook
        WorkSheet workSheet = workBook.DefaultWorkSheet;

        // Convert the worksheet data to a DataTable
        // Set the parameter to true to consider the first row as column headers
        DataTable dataTable = workSheet.ToDataTable(true);

        // Iterate over each row in the DataTable
        foreach (DataRow row in dataTable.Rows)
        {
            // Print each column in the row
            for (int i = 0; i < dataTable.Columns.Count; i++)
            {
                Console.Write($"{row[i]} \t");
            }
            Console.WriteLine(); // Move to the next line after printing each row
        }
    }
}
Imports Microsoft.VisualBasic
Imports IronXL
Imports System
Imports System.Data

Friend Class Program
	Shared Sub Main()
		' Load the Excel workbook from a file
		Dim workBook As WorkBook = WorkBook.Load("sample.xlsx")

		' Access the default worksheet in the workbook
		Dim workSheet As WorkSheet = workBook.DefaultWorkSheet

		' Convert the worksheet data to a DataTable
		' Set the parameter to true to consider the first row as column headers
		Dim dataTable As DataTable = workSheet.ToDataTable(True)

		' Iterate over each row in the DataTable
		For Each row As DataRow In dataTable.Rows
			' Print each column in the row
			For i As Integer = 0 To dataTable.Columns.Count - 1
				Console.Write($"{row(i)} " & vbTab)
			Next i
			Console.WriteLine() ' Move to the next line after printing each row
		Next row
	End Sub
End Class
$vbLabelText   $csharpLabel

In the above code, an Excel file is loaded as a WorkBook object using the WorkBook.Load method provided by IronXL and then accesses its first worksheet data as a WorkSheet. To convert this WorkSheet to a DataTable, the workSheet.ToDataTable method is used to convert and store the data into a new DataTable variable.

Finally, the DataTable data is printed to the console for visualization.

How to Convert Excel to DataTable in C#, Figure 8: Export Data to DataTable Output Export Data to DataTable Output

6. Podsumowanie

The use of DataTable in C# provides a powerful and efficient solution for working with Excel data within applications. By leveraging libraries like IronXL, developers can easily convert Excel data into DataTable and unlock the full potential of C#.

This tutorial explored the capabilities of IronXL and its seamless integration with C#. We discussed the prerequisites for working with Excel files, such as having a compatible development environment, installing the IronXL library, and ensuring the appropriate .NET Framework or .NET Core version.

We also walked through the process of creating a new C# project in Visual Studio and installing IronXL either through the NuGet Package Manager or the Visual Studio Command Line. With IronXL successfully integrated into the project, we demonstrated exporting data to a DataTable using the library's easy-to-use API.

By loading an Excel file, accessing the desired worksheet, and utilizing the ToDataTable method provided by IronXL, we were able to extract the data and store it in a DataTable. Finally, we showcased how to visualize the DataTable by printing its contents in the console.

Using IronXL and DataTable in C#, developers can build robust applications that seamlessly interact with Excel data, enabling efficient data processing, analysis, and visualization. With the knowledge gained from this tutorial, you can now confidently incorporate Excel worksheets into your C# projects and take advantage of the extensive functionality provided by DataTable. For more tutorials on IronXL, please visit the tutorial pages.

Często Zadawane Pytania

Jak mogę przekonwertować plik Excel na DataTable w języku C# bez użycia Interop?

Możesz użyć IronXL do konwersji danych z Excela do tabeli danych (DataTable) w języku C#. Załaduj plik Excel za pomocą metody WorkBook.Load, uzyskaj dostęp do żądanego arkusza i użyj metody workSheet.ToDataTable, aby przeprowadzić konwersję.

Jakie kroki należy wykonać, aby skonfigurować IronXL w projekcie C# do obsługi arkuszy kalkulacyjnych Excel?

Aby skonfigurować IronXL w projekcie C#, upewnij się, że masz zainstalowane Visual Studio, a następnie użyj menedżera pakietów NuGet, aby wyszukać i zainstalować IronXL, lub użyj wiersza poleceń z poleceniem Install-Package IronXl.Excel.

Czy IronXL moze byc uzywany zarówno z .NET Framework, jak i .NET Core?

Tak, IronXL jest kompatybilny zarówno z .NET Framework, jak i .NET Core, co pozwala na elastycznosc w róznych srodowiskach programistycznych do manipulacji danymi Excel.

Czy IronXL obsluguje zarówno formaty XLS, jak i XLSX dla plików Excel?

IronXL obsluguje zarówno formaty XLS, jak i XLSX, co czyni go wszechstronnym narzedziem do obslugi róznych wersji plików Excel.

Jakie sa zalety uzywania IronXL do przetwarzania danych Excel w C#?

IronXL oferuje latwy w uzyciu interfejs API do odczytu, zapisu i manipulacji plikami Excel w C#. Upraszcza procesy importu i eksportu danych oraz obsluguje zaawansowane funkcje, takie jak formatowanie i obsluga formuł.

Jak rozwiazac typowe problemy przy konwersji Excel na DataTable z uzyciem IronXL?

Upewnij sie, ze IronXL jest prawidlowo zainstalowany i dodany do twojego projektu. Sprawdz, czy sciezki do plików Excel sa prawidlowe i ze plik nie jest uzywany przez inny proces. Skonsultuj dokumentacje IronXL w przypadku specyficznych komunikatów bledów.

Jakie srodowisko programistyczne jest zalecane do uzywania IronXL?

Visual Studio jest zalecane do uzywania IronXL, poniewaz zapewnia solidne narzedzia programistyczne i płynna integracje dla projektów C#.

Jak wizualizowac zawartosc DataTable uzyskana z pliku Excel w C#?

Po konwersji danych Excel na DataTable za pomoca IronXL, mozesz iterowac po wierszach i kolumnach DataTable w C#, aby wydrukowac zawartosc do konsoli w celu wizualizacji.

Jordi Bardia
Inżynier oprogramowania
Jordi jest najbardziej biegły w Pythonie, C# i C++. Kiedy nie wykorzystuje swoich umiejętności w Iron Software, programuje gry. Dzieląc odpowiedzialność za testowanie produktów, rozwój produktów i badania, Jordi wnosi ogromną wartość do ciągłej poprawy produktów. Różnorodne doświadczenia ...
Czytaj więcej

Zespol wsparcia Iron

Jestesmy online 24 godziny, 5 dni w tygodniu.
Czat
Email
Zadzwon do mnie