Passer au contenu du pied de page
UTILISATION D'IRONXL
Comment importer un fichier Excel dans une base de données SQL en VB NET

Comment importer un fichier Excel dans une base de données SQL en VB.NET

Two effective administration and analysis tools are SQL databases and Excel, each with special functions and capabilities.

Excel

Excel is a popular spreadsheet program created by Microsoft. Its user-friendly interface and adaptability in managing different data organization, computation, analysis, and visualization activities have earned it a reputation. Users may enter data into Excel sheet cells arranged in rows and columns, carry out mathematical operations, and produce charts, graphs, and pivot tables to summarize and analyze data or import data from Excel. Excel is a widely utilized tool among individuals, corporations, and organizations for many purposes such as financial analysis, inventory management, reporting, and budgeting.

SQL

Structured data is stored, managed, and retrieved using databases that support SQL (Structured Query Language). Their foundation is the relational model, and they are made up of tables with rows and columns. Users may build, change, and query databases using SQL commands and SQL databases such as MySQL, PostgreSQL, SQL Server, and SQLite. These databases offer strong data retrieval and manipulation capabilities, scalability, and integrity assurance.

In this article, we are going to see how VB.NET imports Excel files into the SQL Server database table without using the provider Microsoft.ACE.OLEDB.12.0.

How to Use VB.NET to Import Excel Files to SQL Database

  1. Create a new Visual Studio project.
  2. Install the required library.
  3. Now, we can import an Excel file and convert it into a DataTable or retrieve data.
  4. Connect to the SQL database.
  5. Save the imported data into the database table.
  6. Close the SQL connection and dispose of the object.

What is IronXL

A powerful .NET framework called IronXL was created to facilitate dealing with Excel files written in C#, VB.NET, Visual Basic, and other .NET languages. It is compatible with the XLS and XLSX file formats. This library makes it easier and faster for developers to write, read, edit, and generate Excel spreadsheets. A vast array of tools and functions are also available.

Key features and capabilities of IronXL include:

  • Data handling: IronXL makes it easy to read, write, and manipulate data in Excel spreadsheets. A two-dimensional array may be used to retrieve cells, and computations, formulas, and data formatting are all possible.
  • Excel file creation and altering: In addition to generating new Excel files and altering ones that already exist, developers may also add, remove, and manage worksheets. They can also work with many Excel components.
  • Cross-platform compatibility: IronXL may be utilized in a range of application scenarios and is compatible with multiple .NET platforms, including Xamarin, .NET Core, and .NET Framework, thanks to its cross-platform interoperability.
  • Versatility and compatibility: It supports both the older XLS and the more modern XLSX Excel formats and is compatible with several Excel versions.
  • Support for legacy and modern Excel formats: It can support both more contemporary XML-based formats (XLSX, which dates back to Excel 2007) and more traditional Excel file formats (XLS, which dates back to Excel 97–2003).
  • Usefulness: By offering a straightforward API with easily understood properties and functions, the library makes Excel-related activities more accessible to developers with varying degrees of experience.
  • Data extraction and export: IronXL facilitates the extraction of data from Excel files and the export of Excel data to several formats, making it simple to interface with databases and other systems.
  • Documentation and support: IronXL provides a wealth of documentation, tutorials, and support to assist developers in using its library for Excel-related tasks.
  • Automation and efficiency: By automating Excel tasks, IronXL enables users to be more productive, spend less time on manual labor, and develop data-driven, efficient applications.
  • Integration & customization: It makes it easier to create personalized reports or data-driven solutions by providing choices for exporting Excel data into a variety of formats. It works well with databases and other systems as well.

Financing, data analysis, reporting, business intelligence, and software development are just a few of the numerous fields that employ IronXL. It enables developers to work with Excel files programmatically and produce dependable solutions that combine Excel integration with data manipulation. Click here to learn more.

Create a New Visual Studio Project

It's easy to create a Visual Studio console project. To create a Console Application in Visual Studio, follow these steps:

  1. Launch Visual Studio: Open Visual Studio (make sure your PC has Visual Studio installed).

Start a New Project

Select File, then New, then Project.

How to Import an Excel File to SQL Database in VB .NET: Figure 1 - Console App

Select your preferred programming language, such as C#, from the left panel of the "Create a new project" box.

Next, from the list of available project templates, choose the "Console App" or "Console App (.NET Core)" template.

Give your project a name by filling out the "Name" section.

How to Import an Excel File to SQL Database in VB .NET: Figure 2 - Project Configuration

Select the place where the project should be saved.

To start a new Console application project, click "Create".

How to Import an Excel File to SQL Database in VB .NET: Figure 3 - Create Console App

Installing IronXL Library

To install the IronXL library, follow these steps:

  1. Open the NuGet Package Manager Console by going to Tools > NuGet Package Manager > Package Manager Console.
  2. Use the following command to install the IronXL library:
Install-Package IronXL.Excel

How to Import an Excel File to SQL Database in VB .NET: Figure 4 - Install IronXL

Alternatively, you can also install the IronXL library using the NuGet Package Manager. Just search for the package "IronXL" and choose which of the NuGet packages associated with IronXL you want to download from the list.

How to Import an Excel File to SQL Database in VB .NET: Figure 5 - IronXL

IronXL to Import and Add into SQL Database

These procedures can be used to import data from an Excel file using IronXL and then add it to a SQL database using VB.NET. This example demonstrates how to use IronXL to read an Excel file and insert the data into a SQL Server database.

Imports IronXL
Imports System.Data
Imports System.Data.SqlClient

Module Program
    Sub Main(args As String())

        ' Define the path to the Excel file
        Dim excelFilePath As String = "Demo.xlsx"

        ' Define the connection string to connect to the SQL Server database
        Dim connectionString As String = "Data Source=DESKTOP-QBIBUNV;Initial Catalog=Mohammed;Integrated Security=True;Encrypt=False"

        ' Load the Excel file using IronXL
        Dim workbook As WorkBook = WorkBook.Load(excelFilePath)
        Dim worksheet As WorkSheet = workbook.DefaultWorkSheet

        ' Set up the SQL connection
        Using connection As New SqlConnection(connectionString)
            connection.Open()

            ' Iterate through rows and insert data into SQL database
            For Each row As DataRow In worksheet.ToDataTable().AsEnumerable()

                ' Extract cell data
                Dim cellData As List(Of String) = New List(Of String)()

                For Each cell In row.ItemArray
                    cellData.Add(cell.ToString())
                Next

                ' Insert data into SQL database
                InsertDataIntoSQL(connection, cellData)
            Next
        End Using
    End Sub

    ' Method to insert data into SQL database
    Private Sub InsertDataIntoSQL(connection As SqlConnection, data As List(Of String))

        ' Define your SQL INSERT query
        Dim sqlQuery As String = "INSERT INTO ExcelData (Name, Age) VALUES (@Value1, @Value2)"

        ' Create a SqlCommand object with parameters
        Using command As New SqlCommand(sqlQuery, connection)

            ' Set parameters (adjust as per your column names and data)
            command.Parameters.AddWithValue("@Value1", data(0))
            command.Parameters.AddWithValue("@Value2", data(1))

            ' Execute the SQL command
            command.ExecuteNonQuery()
        End Using
    End Sub
End Module
Imports IronXL
Imports System.Data
Imports System.Data.SqlClient

Module Program
    Sub Main(args As String())

        ' Define the path to the Excel file
        Dim excelFilePath As String = "Demo.xlsx"

        ' Define the connection string to connect to the SQL Server database
        Dim connectionString As String = "Data Source=DESKTOP-QBIBUNV;Initial Catalog=Mohammed;Integrated Security=True;Encrypt=False"

        ' Load the Excel file using IronXL
        Dim workbook As WorkBook = WorkBook.Load(excelFilePath)
        Dim worksheet As WorkSheet = workbook.DefaultWorkSheet

        ' Set up the SQL connection
        Using connection As New SqlConnection(connectionString)
            connection.Open()

            ' Iterate through rows and insert data into SQL database
            For Each row As DataRow In worksheet.ToDataTable().AsEnumerable()

                ' Extract cell data
                Dim cellData As List(Of String) = New List(Of String)()

                For Each cell In row.ItemArray
                    cellData.Add(cell.ToString())
                Next

                ' Insert data into SQL database
                InsertDataIntoSQL(connection, cellData)
            Next
        End Using
    End Sub

    ' Method to insert data into SQL database
    Private Sub InsertDataIntoSQL(connection As SqlConnection, data As List(Of String))

        ' Define your SQL INSERT query
        Dim sqlQuery As String = "INSERT INTO ExcelData (Name, Age) VALUES (@Value1, @Value2)"

        ' Create a SqlCommand object with parameters
        Using command As New SqlCommand(sqlQuery, connection)

            ' Set parameters (adjust as per your column names and data)
            command.Parameters.AddWithValue("@Value1", data(0))
            command.Parameters.AddWithValue("@Value2", data(1))

            ' Execute the SQL command
            command.ExecuteNonQuery()
        End Using
    End Sub
End Module
VB .NET

Using its API, IronXL provides a convenient method for loading Excel files (WorkBook.Load) and retrieving their contents, allowing iteration through rows and cells. This code imports data from the Excel file and inserts it into a SQL database, leveraging data structures and connections for effective data processing.

How to Import an Excel File to SQL Database in VB .NET: Figure 6 - Excel file

Next, the program connects to the SQL Server database using a connection string and the System.Data.SqlClient namespace. SQL INSERT queries are then prepared to insert the Excel data into the corresponding SQL table. The program uses parameterized SQL commands (SqlCommand) to insert the Excel data into the SQL database by mapping the retrieved cell values to the appropriate SQL query parameters and executing the INSERT command using command.ExecuteNonQuery().

How to Import an Excel File to SQL Database in VB .NET: Figure 7 - SQL Server

To learn more about the code, check here.

Conclusion

The IronXL library, which is an Excel object library, is widely used by several industries, including software development, finance, data analysis, and reporting. It is an essential tool for businesses and developers seeking to maximize their operations using Excel. IronXL allows for the creation of dynamic, data-centric applications that efficiently and programmatically manage Excel files.

In summary, using IronXL in a VB.NET application enables seamless data transfer from Excel files to SQL databases, providing efficiency and flexibility in data management across both platforms. IronXL offers a free Community Edition with limitations for non-commercial use. Paid versions, starting at a competitive price, can be purchased through subscription- or perpetual-based licensing models and provide additional features, support, and complete functionality. Please visit IronXL's official website for comprehensive and up-to-date licensing information. For more information on Iron Software products, visit this link.

Questions Fréquemment Posées

Comment puis-je importer des données Excel dans une base de données SQL Server en utilisant VB.NET ?

Vous pouvez importer des données Excel dans une base de données SQL Server en utilisant VB.NET en tirant parti d'IronXL. Tout d'abord, créez un projet Visual Studio, installez la bibliothèque IronXL via le gestionnaire de packages NuGet, chargez le fichier Excel en utilisant l'API d'IronXL, et connectez-vous à la base de données SQL pour insérer les données dans la table de base de données.

Quels sont les avantages d'utiliser IronXL pour la manipulation de fichiers Excel en VB.NET ?

IronXL fournit une solution robuste pour la gestion des fichiers Excel en VB.NET, offrant des fonctionnalités telles que la lecture, l'écriture et la modification de fichiers Excel. Il prend en charge les formats XLS et XLSX et garantit une compatibilité multiplateforme, ce qui le rend idéal pour une intégration fluide des données avec les bases de données SQL.

Puis-je utiliser IronXL pour l'extraction et l'exportation de données à partir de fichiers Excel ?

Oui, IronXL permet aux développeurs d'extraire et d'exporter efficacement des données à partir de fichiers Excel. Il prend en charge des opérations telles que la lecture de valeurs de cellules spécifiques, le parcours des lignes et colonnes, et l'exportation de données vers d'autres formats ou bases de données comme SQL Server.

Quelles sont les étapes pour configurer IronXL dans un projet VB.NET ?

Pour configurer IronXL dans un projet VB.NET, ouvrez votre Visual Studio, accédez à la console du gestionnaire de packages NuGet, et exécutez la commande Install-Package IronXL. Cela installera les bibliothèques nécessaires pour gérer les fichiers Excel par programmation.

Existe-t-il un moyen d'utiliser IronXL sur différentes plateformes .NET ?

IronXL est conçu pour être multiplateforme, prenant en charge divers environnements .NET tels que Xamarin, .NET Core, et .NET Framework. Cela vous assure que vous pouvez utiliser IronXL sur différentes plateformes sans problèmes de compatibilité.

Qu'est-ce qui fait d'IronXL un choix populaire pour l'intégration entre Excel et les bases de données SQL ?

IronXL est apprécié pour sa facilité d'utilisation, ses fonctionnalités complètes pour la manipulation de fichiers Excel, et sa capacité à s'intégrer sans problème avec les bases de données SQL. Il simplifie le processus d'importation et d'exportation de données entre Excel et SQL, améliorant la productivité et l'efficacité de gestion des données.

IronXL propose-t-il une version gratuite, et quelles sont ses limitations ?

IronXL propose une édition communautaire gratuite pour un usage non commercial, qui inclut des fonctionnalités de base avec quelques limitations. Pour des fonctionnalités plus avancées et un support dédié, des versions payantes sont disponibles.

Comment IronXL gère-t-il les différents formats de fichiers Excel ?

IronXL prend en charge à la fois les formats de fichiers Excel anciens (XLS) et modernes (XLSX), permettant aux utilisateurs de travailler avec une large gamme de fichiers Excel sans problèmes de compatibilité, le rendant polyvalent pour divers besoins en gestion de données.

Jordi Bardia
Ingénieur logiciel
Jordi est le plus compétent en Python, C# et C++, et lorsqu'il ne met pas à profit ses compétences chez Iron Software, il programme des jeux. Partageant les responsabilités des tests de produit, du développement de produit et de la recherche, Jordi apporte une immense valeur à l'amé...
Lire la suite