USING IRONXL

How to Convert Excel to Datatable in C# Without oledb

Microsoft Excel is a robust spreadsheet program created by Microsoft. It's a widely used tool for data organization, analysis, and visualization. It is a part of the Office suite from Microsoft. Because of its various features, Excel is a versatile tool that may be used by professionals, individuals, organizations, and universities.

Excel is widely used in a wide range of sectors, including finance, accounting, business analysis, data analysis, research, education, and more. Due to its versatility and extensive feature set, it is the go-to tool for organizing, assessing, and presenting data in both personal and professional situations. In this article, we are going to convert Excel to a DataTable in C# without OLEDB connectivity.

How to Convert Excel to DataTable in C# without OLEDB

  1. Create a new Visual Studio project.
  2. Install the required library.
  3. Load the Excel file into an object.
  4. Convert the Excel sheet data into a DataTable using specific methods.
  5. Use the DataTable as required.

IronXL Library

An alternative to Microsoft Interop for handling Excel files in .NET programs is IronXL. While Microsoft Interop necessitates using the Interop assemblies to connect with Excel, IronXL provides a simpler, more efficient, and more potent way to manipulate Excel files programmatically in .NET environments.

The following are some advantages of using IronXL:

  • Performance and Resource Economy: IronXL outperforms Microsoft Interop in terms of performance and resource efficiency as it is not reliant on the Excel program being installed on the PC.
  • Readability and Simplicity: IronXL offers a simpler API, making it easier to read, write, and manipulate Excel files without the drawbacks of Microsoft Interop.
  • Compatibility and Dependency: IronXL removes dependencies and potential compatibility issues with different Office or Excel versions by not needing Microsoft Excel to be installed on the PC.
  • Platform Independence: While Microsoft Interop is more closely linked to certain Microsoft Office versions, IronXL provides more flexibility and simplicity of deployment in a wider range of settings and platforms.

Because IronXL is faster, easier to use, and requires fewer third-party software installs, it is often a preferable choice for .NET developers who need to work with Excel files programmatically. However, factors like the project's specifics, the pre-existing infrastructure, and the user's familiarity with each library may affect their choice.

Always consider the needs of your application when choosing among these solutions. For further information about the IronXL library, visit this website.

Creating a New Project in Visual Studio

To open Visual Studio, click on File from the menu and select "New Project." Then, choose "Windows Forms Application."

How to Convert Excel to DataTable in C# Without OLEDB: Figure 1

After selecting the file location, enter the project name in the appropriate text area. Next, click the "Create" button and choose the necessary .NET Framework, as seen in the sample below.

How to Convert Excel to DataTable in C# Without OLEDB: Figure 2

The type of application chosen will dictate how the Visual Studio project is structured. To add code, you may enter the Program.cs file and construct or run the application using the console, Windows, or web application.

How to Convert Excel to DataTable in C# Without OLEDB: Figure 3

Next, add the necessary library and test the code.

Installing IronXL Library

To install the IronXL library, open the NuGet Package Manager Console and enter the following command:

Install-Package IronXL.Excel

How to Convert Excel to DataTable in C# Without OLEDB: Figure 4

Alternatively, you can use the NuGet Package Manager to search for the package "IronXL." This will display a list of NuGet packages related to IronXL, from which you can choose the one you need.

How to Convert Excel to DataTable in C# Without OLEDB: Figure 5

Convert Excel File to Data Table

The following code demonstrates how to read an Excel file and convert it into a DataTable after installing the package.

// Necessary namespaces for IronXL and application namespaces
using IronXL;
using System;
using System.Data;
using System.Windows.Forms;

namespace DataTableWindowsForm
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        /// <summary>
        /// Exports data from an Excel file specified by the user through a file dialog.
        /// </summary>
        /// <param name="filename">The name of the file to export data from.</param>
        private void ExportData(string filename)
        {
            string importFilePath = string.Empty;
            openFileDialog1.Filter = "Excel (*.xlsx)|*.xlsx";
            DialogResult result = openFileDialog1.ShowDialog();

            if (result == DialogResult.OK)
            {
                importFilePath = openFileDialog1.FileName;
            }

            if (!string.IsNullOrEmpty(importFilePath))
            {
                // Load the Excel document
                var excelDoc = WorkBook.Load(importFilePath);
                // Select the first worksheet
                var worksheet = excelDoc.WorkSheets[0];
                // Convert worksheet to a DataTable
                DataTable dt = worksheet.ToDataTable();
                // Bind DataTable to the DataGridView
                dataGridView1.DataSource = dt;
            }
        }
    }
}
// Necessary namespaces for IronXL and application namespaces
using IronXL;
using System;
using System.Data;
using System.Windows.Forms;

namespace DataTableWindowsForm
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        /// <summary>
        /// Exports data from an Excel file specified by the user through a file dialog.
        /// </summary>
        /// <param name="filename">The name of the file to export data from.</param>
        private void ExportData(string filename)
        {
            string importFilePath = string.Empty;
            openFileDialog1.Filter = "Excel (*.xlsx)|*.xlsx";
            DialogResult result = openFileDialog1.ShowDialog();

            if (result == DialogResult.OK)
            {
                importFilePath = openFileDialog1.FileName;
            }

            if (!string.IsNullOrEmpty(importFilePath))
            {
                // Load the Excel document
                var excelDoc = WorkBook.Load(importFilePath);
                // Select the first worksheet
                var worksheet = excelDoc.WorkSheets[0];
                // Convert worksheet to a DataTable
                DataTable dt = worksheet.ToDataTable();
                // Bind DataTable to the DataGridView
                dataGridView1.DataSource = dt;
            }
        }
    }
}
' Necessary namespaces for IronXL and application namespaces
Imports IronXL
Imports System
Imports System.Data
Imports System.Windows.Forms

Namespace DataTableWindowsForm
	Partial Public Class Form1
		Inherits Form

		Public Sub New()
			InitializeComponent()
		End Sub

		''' <summary>
		''' Exports data from an Excel file specified by the user through a file dialog.
		''' </summary>
		''' <param name="filename">The name of the file to export data from.</param>
		Private Sub ExportData(ByVal filename As String)
			Dim importFilePath As String = String.Empty
			openFileDialog1.Filter = "Excel (*.xlsx)|*.xlsx"
			Dim result As DialogResult = openFileDialog1.ShowDialog()

			If result = System.Windows.Forms.DialogResult.OK Then
				importFilePath = openFileDialog1.FileName
			End If

			If Not String.IsNullOrEmpty(importFilePath) Then
				' Load the Excel document
				Dim excelDoc = WorkBook.Load(importFilePath)
				' Select the first worksheet
				Dim worksheet = excelDoc.WorkSheets(0)
				' Convert worksheet to a DataTable
				Dim dt As DataTable = worksheet.ToDataTable()
				' Bind DataTable to the DataGridView
				dataGridView1.DataSource = dt
			End If
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel

In the above code:

  • The Windows Form loads the Excel files and converts them into a new DataTable.
  • It uses an open file dialog to let the user choose an Excel file.
  • The WorkBook.Load() method from IronXL is used to load the Excel file into a Workbook object.
  • The first worksheet is selected using an index or name.
  • The ToDataTable method is used to turn the worksheet data into a DataTable.
  • The filled DataTable is set as the data source for a DataGridView control on the Windows Form.

At the bottom, a form and a button load the Excel file into the application.

How to Convert Excel to DataTable in C# Without OLEDB: Figure 6

When the user clicks the "Load Excel" button, it will prompt a dialog allowing the user to select a file.

How to Convert Excel to DataTable in C# Without OLEDB: Figure 7

It will then process the selected file, convert it into a DataTable, and load it into a DataGridView.

How to Convert Excel to DataTable in C# Without OLEDB: Figure 8

Learn more about using IronXL with DataTables.

Conclusion

IronXL is one of the most commonly used Excel add-ons that does not depend on any extra external libraries. Installing Microsoft Excel is unnecessary as it is a self-contained program. It can manipulate Excel files in various ways. In contrast, the Interop library requires other libraries to parse files and edit Word documents.

IronXL provides a comprehensive solution for any programming process using Microsoft Excel documents, including operations like calculations, sorting, merging, and file storage. It facilitates handling Excel data, reading, and writing files more efficiently.

Originally, IronXL was priced at $749. Users can receive software updates and support by paying a one-year membership fee. IronXL also offers protection against illegal redistribution for a fee. Click here to try IronXL with a free trial for more detailed pricing information. Visit the Iron Software home page for further information on other Iron software products.

Frequently Asked Questions

What is the purpose of this tutorial?

The tutorial aims to guide users on how to convert Excel to a DataTable in C# without using OLEDB connectivity, utilizing the IronXL library instead.

Why should I use IronXL over Microsoft Interop for Excel operations?

IronXL is preferred over Microsoft Interop because it offers better performance, resource economy, and simplicity. It does not require Microsoft Excel to be installed on the PC, thus avoiding compatibility issues with different Office versions.

How can I install the IronXL library in my project?

You can install the IronXL library by opening the NuGet Package Manager Console in Visual Studio and running the command 'Install-Package IronXL'. Alternatively, use the NuGet Package Manager to search for and install IronXL.

What are the steps to convert an Excel file to a DataTable using IronXL?

First, create a new Visual Studio project and install IronXL. Load the Excel file using IronXL's 'WorkBook.Load()' method, select the worksheet, and use the 'ToDataTable' method to convert the worksheet data into a DataTable.

Can I use IronXL with any version of Excel?

Yes, IronXL is platform-independent and does not require any specific version of Microsoft Excel to be installed, making it compatible with various settings and platforms.

What are the benefits of using IronXL for data manipulation?

IronXL provides excellent performance, is easy to use, and requires fewer third-party software installations. It allows for efficient reading, writing, and manipulation of Excel files in .NET applications.

Does IronXL require Microsoft Excel to be installed on my computer?

No, IronXL does not require Microsoft Excel to be installed on your computer, which eliminates dependency and compatibility issues.

Is there a trial version available for IronXL?

Yes, IronXL offers a free trial version that allows users to explore its features before purchasing a license. More details are available on their website.

What types of applications can benefit from using IronXL?

Applications that require Excel data manipulation, such as data analysis tools, business intelligence applications, and any .NET applications that process Excel files, can benefit from using IronXL.

How does IronXL handle Excel files programmatically?

IronXL allows developers to load, read, and manipulate Excel files programmatically without relying on Excel's installed components, using a straightforward API for efficient file handling in .NET.

Regan Pun
Software Engineer
Regan graduated from the University of Reading, with a BA in Electronic Engineering. Before joining Iron Software, his previous job roles had him laser-focused on single tasks; and what he most enjoys at Iron Software is the spectrum of work he gets to undertake, whether it’s adding value to sales, technical support, product development or marketing. He enjoys understanding the way developers are using the Iron Software library, and using that knowledge to continually improve documentation and develop the products.
< PREVIOUS
Work with Excel Files Without Microsoft Office in C#
NEXT >
How to Concatenate or Merge Excel Files in C# Combine XLS