How to Read Excel Data and Insert to Database Table in C#

In this tutorial, you'll learn how to import Excel data into a SQL database using C# and the IronXL library. The process begins by setting up the necessary environment in Visual Studio, including the installation of System.Data.SqlClient and IronXL packages. You'll create a new SQL database and table to store the imported data.

The IronXL library is used to load the Excel file, converting it into a dataset for processing. Using SQL commands, the dataset's rows are iteratively inserted into the database table. The tutorial provides a detailed explanation of establishing a connection to the SQL Server, utilizing SQL Data Adapter objects, and executing parameterized SQL commands. By the end of the tutorial, you will have successfully transferred data from an Excel file to a SQL database, with the ability to verify the results by viewing the database table contents.

IronXL simplifies handling Excel files in C# applications, making it a versatile tool for data migration tasks. For further exploration and practice, you are encouraged to try out different functionalities of IronXL.

Below is a code example illustrating the described process. This sample demonstrates how to connect to an SQL database, read an Excel file, and insert its data into a database table.

using System;
using System.Data.SqlClient;
using IronXL;

// This C# program reads an Excel file and inserts its data into a SQL database table.
class ExcelToSqlImporter
{
    static void Main()
    {
        // Define the connection string for the SQL Server
        string connectionString = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;";

        // Open a connection to the database
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            connection.Open();
            Console.WriteLine("Database connection opened successfully.");

            // Load the Excel file into the IronXL WorkBook
            WorkBook workbook = WorkBook.Load("example.xlsx");
            WorkSheet sheet = workbook.WorkSheets.First();

            // Iterate over the rows in the Excel sheet
            foreach (var row in sheet.Rows)
            {
                // Retrieve cell data
                string column1 = row["A"].Text;
                string column2 = row["B"].Text;
                string column3 = row["C"].Text;

                // Define the SQL Insert command with parameters
                string sqlInsert = "INSERT INTO MyTable (Column1, Column2, Column3) VALUES (@column1, @column2, @column3)";

                using (SqlCommand command = new SqlCommand(sqlInsert, connection))
                {
                    // Set the parameter values
                    command.Parameters.AddWithValue("@column1", column1);
                    command.Parameters.AddWithValue("@column2", column2);
                    command.Parameters.AddWithValue("@column3", column3);

                    // Execute the command
                    command.ExecuteNonQuery();
                }
            }

            Console.WriteLine("Data imported successfully.");
        }
    }
}
using System;
using System.Data.SqlClient;
using IronXL;

// This C# program reads an Excel file and inserts its data into a SQL database table.
class ExcelToSqlImporter
{
    static void Main()
    {
        // Define the connection string for the SQL Server
        string connectionString = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;";

        // Open a connection to the database
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            connection.Open();
            Console.WriteLine("Database connection opened successfully.");

            // Load the Excel file into the IronXL WorkBook
            WorkBook workbook = WorkBook.Load("example.xlsx");
            WorkSheet sheet = workbook.WorkSheets.First();

            // Iterate over the rows in the Excel sheet
            foreach (var row in sheet.Rows)
            {
                // Retrieve cell data
                string column1 = row["A"].Text;
                string column2 = row["B"].Text;
                string column3 = row["C"].Text;

                // Define the SQL Insert command with parameters
                string sqlInsert = "INSERT INTO MyTable (Column1, Column2, Column3) VALUES (@column1, @column2, @column3)";

                using (SqlCommand command = new SqlCommand(sqlInsert, connection))
                {
                    // Set the parameter values
                    command.Parameters.AddWithValue("@column1", column1);
                    command.Parameters.AddWithValue("@column2", column2);
                    command.Parameters.AddWithValue("@column3", column3);

                    // Execute the command
                    command.ExecuteNonQuery();
                }
            }

            Console.WriteLine("Data imported successfully.");
        }
    }
}
Imports System
Imports System.Data.SqlClient
Imports IronXL

' This C# program reads an Excel file and inserts its data into a SQL database table.
Friend Class ExcelToSqlImporter
	Shared Sub Main()
		' Define the connection string for the SQL Server
		Dim connectionString As String = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;"

		' Open a connection to the database
		Using connection As New SqlConnection(connectionString)
			connection.Open()
			Console.WriteLine("Database connection opened successfully.")

			' Load the Excel file into the IronXL WorkBook
			Dim workbook As WorkBook = WorkBook.Load("example.xlsx")
			Dim sheet As WorkSheet = workbook.WorkSheets.First()

			' Iterate over the rows in the Excel sheet
			For Each row In sheet.Rows
				' Retrieve cell data
				Dim column1 As String = row("A").Text
				Dim column2 As String = row("B").Text
				Dim column3 As String = row("C").Text

				' Define the SQL Insert command with parameters
				Dim sqlInsert As String = "INSERT INTO MyTable (Column1, Column2, Column3) VALUES (@column1, @column2, @column3)"

				Using command As New SqlCommand(sqlInsert, connection)
					' Set the parameter values
					command.Parameters.AddWithValue("@column1", column1)
					command.Parameters.AddWithValue("@column2", column2)
					command.Parameters.AddWithValue("@column3", column3)

					' Execute the command
					command.ExecuteNonQuery()
				End Using
			Next row

			Console.WriteLine("Data imported successfully.")
		End Using
	End Sub
End Class
$vbLabelText   $csharpLabel

Further Reading: How to Read Excel Data and Insert to Database Table in C#

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
How to Read CSV files in C# using IronXL
NEXT >
How to Convert a Data Table to an Excel File