跳至页脚内容
使用 IRONXL

如何在 C# 中将 Excel 导入 SQL Server

In many different business contexts, importing data from Excel into SQL Server is a typical necessity. Reading data from an Excel file and entering it into an SQL Server database are the tasks involved in this activity. While the export wizard is often used, IronXL provides a more programmatic and flexible approach to data handling. IronXL is a powerful C# library that can import Excel data from files; therefore, it's possible to expedite this operation. To that end, this post will offer a thorough how-to guide that addresses the configuration, execution, and enhancement of the import Excel to SQL Server using C#.

How to Import Excel to SQL Server in C#: Figure 1 - IronXL: The C# Excel Library

How to Import Excel to SQL Server in C#

  1. Set Up Your Development Environment
  2. Prepare Your Excel File
  3. Connect to Your SQL Server Database
  4. Read Data from Excel Files Using IronXL
  5. Export Data and Generate a PDF Report Using IronPDF
  6. Review the PDF Report

What is IronXL?

IronXL, sometimes referred to as IronXL.Excel, is a feature-rich C# library made to make working with Excel files in .NET applications easier. This robust tool is ideal for server-side applications since it enables developers to read, create, and edit Excel files without needing to install Microsoft Excel on the computer. Excel 2007 and later (.xlsx) and Excel 97–2003 (.xls) formats are supported by IronXL, providing versatility in managing various Excel file versions. It allows for significant data manipulation, such as manipulating worksheets, rows, and columns in addition to inserting, updating, and removing data.

IronXL also supports cell formatting and Excel formulas, enabling the programmed generation of complex and well-formatted spreadsheets. With its performance optimization and compatibility with multiple .NET platforms, including .NET Framework, .NET Core, and .NET 5/6, IronXL guarantees effective handling of huge datasets. It is a flexible option for developers wishing to integrate Excel file operations into their applications, whether for straightforward data import/export activities or intricate reporting systems, thanks to its smooth interface with other .NET frameworks.

Key Features

Read and Write Excel Files

Developers can read and write data to and from Excel files using IronXL. It's simple to make new Excel files and edit ones that already exist.

No Installation Required for Microsoft Excel

IronXL does not require the installation of Microsoft Excel on the computer that is hosting the application, in contrast to certain other libraries. It's perfect for server-side apps because of this.

Support for Various Excel Formats

The library offers versatility in managing various Excel file types by supporting the .xls (Excel 97-2003) and .xlsx (Excel 2007 and later) formats.

Create a New Visual Studio Project

A Visual Studio console project is simple to create. In Visual Studio, take the following actions to create a Console Application:

  1. Open Visual Studio: Make sure you have installed Visual Studio on your computer before opening it.
  2. Start a New Project: Choose File -> New -> Project.

How to Import Excel to SQL Server in C#: Figure 2 - Click New

  1. From the Create a new project box's left panel, choose your preferred programming language—for example, C#.
  2. Select the Console App or Console App (.NET Core) template from the list of available project templates.
  3. In the Name area, give your project a name.

How to Import Excel to SQL Server in C#: Figure 3 - Provide a name and a save location

  1. Decide on a location to save the project.
  2. Click Create to launch an application project for a Console.

How to Import Excel to SQL Server in C#: Figure 4 - Finally click create to launch an application

Installing IronXL Library

Installing the IronXL library is required because of the upcoming update. Lastly, to finish the procedure, launch the NuGet Package Manager Console and type the following command:

Install-Package IronXL.Excel

How to Import Excel to SQL Server in C#: Figure 5 - Input the above command in the NuGet Package Manager Console to install IronXL

Using the NuGet Package Manager to search for the IronXL package is another method. This allows us to select which of the NuGet packages linked to IronXL to download.

How to Import Excel to SQL Server in C#: Figure 6 - Alternatively search for IronXL using the NuGet Package Manager and install it

Import Excel to SQL with IronXL

Reading Data from Excel Using IronXL

The process of reading data from Excel files is made easier with IronXL. The example that follows shows you how to use IronXL to read data from an Excel file. With this approach, the data is read and saved in a list of dictionaries, each of which corresponds to a row in the Excel sheet.

using IronXL;
using System;
using System.Collections.Generic;

public class ExcelReader
{
    public static List<Dictionary<string, object>> ReadExcelFile(string filePath)
    {
        // Initialize a list to store data from Excel
        var data = new List<Dictionary<string, object>>();

        // Load the workbook from the file path provided
        WorkBook workbook = WorkBook.Load(filePath);

        // Access the first worksheet in the workbook
        WorkSheet sheet = workbook.WorkSheets[0];

        // Retrieve column headers from the first row
        var headers = new List<string>();
        foreach (var header in sheet.Rows[0].Columns)
        {
            headers.Add(header.ToString());
        }

        // Loop through each row starting from the second row
        for (int i = 1; i < sheet.Rows.Count; i++)
        {
            // Create a dictionary to store the row data associated with column headers
            var rowData = new Dictionary<string, object>();
            for (int j = 0; j < headers.Count; j++)
            {
                rowData[headers[j]] = sheet.Rows[i][j].Value;
            }
            data.Add(rowData);
        }

        return data;
    }
}
using IronXL;
using System;
using System.Collections.Generic;

public class ExcelReader
{
    public static List<Dictionary<string, object>> ReadExcelFile(string filePath)
    {
        // Initialize a list to store data from Excel
        var data = new List<Dictionary<string, object>>();

        // Load the workbook from the file path provided
        WorkBook workbook = WorkBook.Load(filePath);

        // Access the first worksheet in the workbook
        WorkSheet sheet = workbook.WorkSheets[0];

        // Retrieve column headers from the first row
        var headers = new List<string>();
        foreach (var header in sheet.Rows[0].Columns)
        {
            headers.Add(header.ToString());
        }

        // Loop through each row starting from the second row
        for (int i = 1; i < sheet.Rows.Count; i++)
        {
            // Create a dictionary to store the row data associated with column headers
            var rowData = new Dictionary<string, object>();
            for (int j = 0; j < headers.Count; j++)
            {
                rowData[headers[j]] = sheet.Rows[i][j].Value;
            }
            data.Add(rowData);
        }

        return data;
    }
}
Imports IronXL
Imports System
Imports System.Collections.Generic

Public Class ExcelReader
	Public Shared Function ReadExcelFile(ByVal filePath As String) As List(Of Dictionary(Of String, Object))
		' Initialize a list to store data from Excel
		Dim data = New List(Of Dictionary(Of String, Object))()

		' Load the workbook from the file path provided
		Dim workbook As WorkBook = WorkBook.Load(filePath)

		' Access the first worksheet in the workbook
		Dim sheet As WorkSheet = workbook.WorkSheets(0)

		' Retrieve column headers from the first row
		Dim headers = New List(Of String)()
		For Each header In sheet.Rows(0).Columns
			headers.Add(header.ToString())
		Next header

		' Loop through each row starting from the second row
		For i As Integer = 1 To sheet.Rows.Count - 1
			' Create a dictionary to store the row data associated with column headers
			Dim rowData = New Dictionary(Of String, Object)()
			For j As Integer = 0 To headers.Count - 1
				rowData(headers(j)) = sheet.Rows(i)(j).Value
			Next j
			data.Add(rowData)
		Next i

		Return data
	End Function
End Class
$vbLabelText   $csharpLabel

Connecting to SQL Server

Use the SqlConnection class from the System.Data.SqlClient namespace to establish a connection to SQL Server. Make sure you have the right connection string, which normally consists of the database name, server name, and authentication information. How to connect to a SQL Server database and add data is covered in the following example.

using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;

public class SqlServerConnector
{
    private string connectionString;

    // Constructor accepts a connection string
    public SqlServerConnector(string connectionString)
    {
        this.connectionString = connectionString;
    }

    // Inserts data into the specified table
    public void InsertData(Dictionary<string, object> data, string tableName)
    {
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            connection.Open();

            // Construct an SQL INSERT command with parameterized values to prevent SQL injection
            var columns = string.Join(",", data.Keys);
            var parameters = string.Join(",", data.Keys.Select(key => "@" + key));
            string query = $"INSERT INTO {tableName} ({columns}) VALUES ({parameters})";

            using (SqlCommand command = new SqlCommand(query, connection))
            {
                // Add parameters to the command
                foreach (var kvp in data)
                {
                    command.Parameters.AddWithValue("@" + kvp.Key, kvp.Value ?? DBNull.Value);
                }

                // Execute the command
                command.ExecuteNonQuery();
            }
        }
    }
}
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;

public class SqlServerConnector
{
    private string connectionString;

    // Constructor accepts a connection string
    public SqlServerConnector(string connectionString)
    {
        this.connectionString = connectionString;
    }

    // Inserts data into the specified table
    public void InsertData(Dictionary<string, object> data, string tableName)
    {
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            connection.Open();

            // Construct an SQL INSERT command with parameterized values to prevent SQL injection
            var columns = string.Join(",", data.Keys);
            var parameters = string.Join(",", data.Keys.Select(key => "@" + key));
            string query = $"INSERT INTO {tableName} ({columns}) VALUES ({parameters})";

            using (SqlCommand command = new SqlCommand(query, connection))
            {
                // Add parameters to the command
                foreach (var kvp in data)
                {
                    command.Parameters.AddWithValue("@" + kvp.Key, kvp.Value ?? DBNull.Value);
                }

                // Execute the command
                command.ExecuteNonQuery();
            }
        }
    }
}
Imports System
Imports System.Collections.Generic
Imports System.Data.SqlClient
Imports System.Linq

Public Class SqlServerConnector
	Private connectionString As String

	' Constructor accepts a connection string
	Public Sub New(ByVal connectionString As String)
		Me.connectionString = connectionString
	End Sub

	' Inserts data into the specified table
	Public Sub InsertData(ByVal data As Dictionary(Of String, Object), ByVal tableName As String)
		Using connection As New SqlConnection(connectionString)
			connection.Open()

			' Construct an SQL INSERT command with parameterized values to prevent SQL injection
			Dim columns = String.Join(",", data.Keys)
			Dim parameters = String.Join(",", data.Keys.Select(Function(key) "@" & key))
			Dim query As String = $"INSERT INTO {tableName} ({columns}) VALUES ({parameters})"

			Using command As New SqlCommand(query, connection)
				' Add parameters to the command
				For Each kvp In data
					command.Parameters.AddWithValue("@" & kvp.Key, If(kvp.Value, DBNull.Value))
				Next kvp

				' Execute the command
				command.ExecuteNonQuery()
			End Using
		End Using
	End Sub
End Class
$vbLabelText   $csharpLabel

Combining IronXL with SQL Server

Once the logic for reading Excel files and inserting data into an SQL database has been established, integrate these features to finish the import process. The application that follows receives information from an Excel file and adds it to a Microsoft SQL Server database.

using System;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        // Define the path to the Excel file, SQL connection string, and target table name
        string excelFilePath = "path_to_your_excel_file.xlsx";
        string connectionString = "your_sql_server_connection_string";
        string tableName = "your_table_name";

        // Read data from Excel
        List<Dictionary<string, object>> excelData = ExcelReader.ReadExcelFile(excelFilePath);

        // Create an instance of the SQL connector and insert data
        SqlServerConnector sqlConnector = new SqlServerConnector(connectionString);
        foreach (var row in excelData)
        {
            sqlConnector.InsertData(row, tableName);
        }

        Console.WriteLine("Data import completed successfully.");
    }
}
using System;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        // Define the path to the Excel file, SQL connection string, and target table name
        string excelFilePath = "path_to_your_excel_file.xlsx";
        string connectionString = "your_sql_server_connection_string";
        string tableName = "your_table_name";

        // Read data from Excel
        List<Dictionary<string, object>> excelData = ExcelReader.ReadExcelFile(excelFilePath);

        // Create an instance of the SQL connector and insert data
        SqlServerConnector sqlConnector = new SqlServerConnector(connectionString);
        foreach (var row in excelData)
        {
            sqlConnector.InsertData(row, tableName);
        }

        Console.WriteLine("Data import completed successfully.");
    }
}
Imports System
Imports System.Collections.Generic

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Define the path to the Excel file, SQL connection string, and target table name
		Dim excelFilePath As String = "path_to_your_excel_file.xlsx"
		Dim connectionString As String = "your_sql_server_connection_string"
		Dim tableName As String = "your_table_name"

		' Read data from Excel
		Dim excelData As List(Of Dictionary(Of String, Object)) = ExcelReader.ReadExcelFile(excelFilePath)

		' Create an instance of the SQL connector and insert data
		Dim sqlConnector As New SqlServerConnector(connectionString)
		For Each row In excelData
			sqlConnector.InsertData(row, tableName)
		Next row

		Console.WriteLine("Data import completed successfully.")
	End Sub
End Class
$vbLabelText   $csharpLabel

This class is in charge of using IronXL to read the data from the given Excel file. The ReadExcelFile function loads the Excel workbook, opens the first worksheet, and gathers data by looping through the rows of the data worksheet. To facilitate handling the tables, the information is kept in a list of dictionaries.

How to Import Excel to SQL Server in C#: Figure 7 - Example Input Excel file

The data is inserted into the designated database table by this class, which also manages the connection to the SQL Server database. The InsertData method employs parameterized queries to prevent SQL injection and builds an SQL INSERT query dynamically based on the dictionary's keys, which stand in for column names.

Using the ExcelReader class to read the data into the SQL table from the Excel file and the SqlServerConnector class to insert each row into the SQL Server table, the Main function manages the entire process.

How to Import Excel to SQL Server in C#: Figure 8 - Output showcasing successful query on the SQL Server

Error handling and optimization are crucial for ensuring a robust and efficient import process. Implementing robust error handling can manage potential issues such as missing files, invalid data formats, and SQL exceptions. Here’s an example of incorporating error handling.

try
{
    // Insert the importing logic here
}
catch (Exception ex)
{
    Console.WriteLine("An error occurred: " + ex.Message);
}
try
{
    // Insert the importing logic here
}
catch (Exception ex)
{
    Console.WriteLine("An error occurred: " + ex.Message);
}
Try
	' Insert the importing logic here
Catch ex As Exception
	Console.WriteLine("An error occurred: " & ex.Message)
End Try
$vbLabelText   $csharpLabel

Conclusion

Finally, an effective and reliable method for managing Excel files within .NET applications is to import data from Excel into an MS SQL database using C# and IronXL. IronXL is compatible with multiple Excel formats and has strong capabilities that make reading and writing Excel data easier without the need to install Microsoft Excel. Through the integration of System.Data.SqlClient with IronXL, developers can easily move data between SQL Servers using parameterized queries to improve security and prevent SQL injection.

Finally, adding IronXL and Iron Software to your toolset for .NET development allows you to efficiently manipulate Excel, create PDFs, do OCR, and utilize barcodes. Combining Iron Software's flexible suite with IronXL's simplicity of use, interoperability, and performance guarantees streamlined development and improved application capabilities. With clear license options that are customized to the requirements of the project, developers may select the right model with confidence. By utilizing these benefits, developers can effectively tackle a range of difficulties while maintaining compliance and openness.

常见问题解答

用 C# 将 Excel 数据导入 SQL Server 的最佳方法是什么?

使用 IronXL 库,您可以高效地将 Excel 数据导入 SQL Server,无需安装 Microsoft Excel。

如何在不使用 Microsoft Excel 的情况下在 C# 中读取 Excel 文件?

IronXL 允许您在 C# 中读取 Excel 文件,无需 Microsoft Excel。您可以加载 Excel 工作簿、访问工作表和提取数据。

在 C# 应用程序中连接 Excel 文件到 SQL Server 的步骤是什么?

首先,使用 IronXL 读取 Excel 文件。然后,使用 SqlConnection 类建立与 SQL Server 的连接,并使用 SqlCommand 将数据插入 SQL 数据库。

为什么我应该在 .NET 应用程序中使用 IronXL 进行 Excel 操作?

IronXL 提供高效的数据处理功能,与多个 .NET 平台兼容,并且不需要安装 Excel,非常适合服务器端应用程序和处理大型数据集。

如何在 C# 中处理大型 Excel 数据集?

IronXL 为大型数据集提供强大的支持,使您能够高效读取和操作 Excel 文件中的数据,并将其集成到应用程序中而不会出现性能问题。

将 Excel 导入 SQL Server 时应使用哪些错误处理策略?

实现 try-catch 块以处理潜在错误,例如文件未找到、数据格式无效或 SQL 异常,以确保导入过程顺利进行。

我可以在 C# 应用程序中自动导入 Excel 数据到 SQL Server 吗?

可以,使用 IronXL,您可以通过编写一个 C# 应用程序,最小化人工干预地读取 Excel 文件并将数据插入 SQL Server 来自动化导入过程。

如何通过参数化查询防止 C# 中的 SQL 注入?

在 C# 中使用参数化查询允许您通过在 SQL 命令中为参数使用占位符安全地将数据插入 SQL Server,这有助于防止 SQL 注入攻击。

如何优化将 Excel 数据导入 SQL Server 的性能?

通过批量插入、使用 IronXL 高效处理大型数据集,并确保您的 SQL Server 连接和命令已正确配置以优化性能。

在项目中使用 IronXL 的许可选项是什么?

IronXL 提供灵活的许可选项,根据项目需求进行定制,使开发人员可以选择最适合其应用程序需求和预算的计划。

Curtis Chau
技术作家

Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。

除了开发之外,Curtis 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。