跳至页脚内容
使用 IRONXL

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

在许多不同的商业环境中,将数据从 Excel 导入 SQL Server 是一项典型的必要操作。 这项活动涉及的任务包括:从 Excel 文件中读取数据并将其输入到 SQL Server 数据库中。 虽然导出向导经常被使用,但 IronXL 提供了一种更程序化、更灵活的数据处理方法。 IronXL 是一个功能强大的 C# 库,可以从文件中导入 Excel 数据; 因此,有可能加快这项操作。 为此,本文将提供一个全面的操作指南,介绍如何使用 C# 配置、执行和增强将 Excel 导入 SQL Server 的功能。

如何在 C# 中将 Excel 导入 SQL Server:图 1 - IronXL:C# Excel 库

如何使用 C# 将 Excel 导入 SQL Server

  1. 设置开发环境
  2. 准备您的 Excel 文件
  3. 连接到您的 SQL Server 数据库
  4. 使用 IronXL 从 Excel 文件中读取数据
  5. 使用 IronPDF 导出数据并生成 PDF 报告
  6. 查看PDF报告

什么是 IronXL?

IronXL,有时也称为 IronXL.Excel,是一个功能丰富的 C# 库,旨在简化 .NET 应用程序中处理 Excel 文件的操作。 这款功能强大的工具非常适合服务器端应用程序,因为它使开发人员能够读取、创建和编辑 Excel 文件,而无需在计算机上安装 Microsoft Excel。 IronXL 支持 Excel 2007 及更高版本 (.xlsx) 和 Excel 97–2003 (.xls) 格式,在管理各种 Excel 文件版本方面提供了灵活性。 它允许进行大量的数据操作,例如操作工作表、行和列,以及插入、更新和删除数据。

IronXL 还支持单元格格式设置和 Excel 公式,能够以编程方式生成复杂且格式良好的电子表格。 IronXL 具有性能优化,并兼容多个 .NET 平台,包括 .NET Framework、.NET Core 和 .NET 5/6,能够有效处理海量数据集。 对于希望将 Excel 文件操作集成到其应用程序中的开发人员来说,无论是简单的数据导入/导出活动还是复杂的报告系统,它都是一个灵活的选择,因为它与其他 .NET 框架的接口非常流畅。

主要功能

读取和写入 Excel 文件

开发人员可以使用 IronXL 从 Excel 文件读取和写入数据。 创建新的 Excel 文件和编辑现有文件都很简单。

无需安装 Microsoft Excel

与某些其他库不同,IronXL 不需要在运行该应用程序的计算机上安装 Microsoft Excel。 因此,它非常适合服务器端应用程序。

支持多种Excel格式

该库通过支持 .xls(Excel 97-2003)和 .xlsx(Excel 2007 及更高版本)格式,提供了管理各种 Excel 文件类型的多功能性。

创建新的Visual Studio项目

创建 Visual Studio 控制台项目很简单。 在 Visual Studio 中,执行以下操作以创建控制台应用程序:

1.打开 Visual Studio :请确保在打开之前已在计算机上安装了 Visual Studio。 2.开始一个新项目:选择File -> New -> Project

如何在 C# 中将 Excel 导入 SQL Server:图 2 - 单击"新建"

  1. Create a new project框的左侧面板中,选择您喜欢的编程语言——例如 C#。
  2. 从可用项目模板列表中选择Console AppConsole App (.NET Core)模板。
  3. "名称"区域,给你的项目起个名字。

如何在 C# 中将 Excel 文件导入 SQL Server:图 3 - 提供名称和保存位置

  1. 确定项目保存位置。
  2. 单击"创建"以启动控制台应用程序项目。

如何在 C# 中将 Excel 导入 SQL Server:图 4 - 最后单击"创建"以启动应用程序

安装IronXL库

由于即将进行更新,因此需要安装 IronXL 库。 最后,要完成此过程,请启动 NuGet 包管理器控制台并键入以下命令:

Install-Package IronXL.Excel

如何在 C# 中将 Excel 导入 SQL Server:图 5 - 在 NuGet 包管理器控制台中输入上述命令以安装 IronXL

使用 NuGet 包管理器搜索IronXL包是另一种方法。 这样我们就可以选择要下载与 IronXL 关联的哪些 NuGet 包。

如何在 C# 中将 Excel 导入 SQL Server:图 6 - 或者,使用 NuGet 包管理器搜索 IronXL 并安装它。

使用 IronXL 将 Excel 导入 SQL

使用 IronXL 从 Excel 读取数据

使用 IronXL 可以更轻松地从 Excel 文件中读取数据。 以下示例展示了如何使用 IronXL 从 Excel 文件中读取数据。这种方法会将数据读取并保存到一个字典列表中,每个字典对应于 Excel 工作表中的一行。

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

正在连接到 SQL Server

使用System.Data.SqlClient命名空间中的SqlConnection类建立与 SQL Server 的连接。 请确保您拥有正确的连接字符串,该字符串通常由数据库名称、服务器名称和身份验证信息组成。 以下示例介绍了如何连接到 SQL Server 数据库并添加数据。

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

将 IronXL 与 SQL Server 结合使用

一旦建立了读取 Excel 文件并将数据插入 SQL 数据库的逻辑,就将这些功能集成起来以完成导入过程。 接下来的应用程序会从 Excel 文件接收信息,并将其添加到 Microsoft SQL Server 数据库中。

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

该类负责使用 IronXL 从指定的 Excel 文件中读取数据。ReadExcelFile ReadExcelFile加载 Excel 工作簿,打开第一个工作表,并通过遍历数据工作表的每一行来收集数据。 为了便于处理表格,信息保存在字典列表中。

如何在 C# 中将 Excel 文件导入 SQL Server:图 7 - 示例输入 Excel 文件

该类会将数据插入到指定的数据库表中,同时还会管理与 SQL Server 数据库的连接。 InsertData方法采用参数化查询来防止 SQL 注入,并根据字典的键(代表列名)动态构建 SQL INSERT 查询。

Main函数使用ExcelReader类从 Excel 文件读取数据到 SQL 表中,并使用SqlServerConnector类将每一行插入到 SQL Server 表中,从而管理整个过程。

如何在 C# 中将 Excel 导入 SQL Server:图 8 - 输出结果展示了 SQL Server 上的成功查询

错误处理和优化对于确保稳健高效的导入过程至关重要。 实施健全的错误处理机制可以管理诸如文件丢失、数据格式无效和 SQL 异常等潜在问题。 以下是加入错误处理的示例。

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

结论

最后,在 .NET 应用程序中管理 Excel 文件的一种有效且可靠的方法是使用 C# 和 IronXL 将数据从 Excel 导入到 MS SQL 数据库中。 IronXL 兼容多种 Excel 格式,并具有强大的功能,无需安装 Microsoft Excel 即可轻松读取和写入 Excel 数据。 通过将System.Data.SqlClient与 IronXL 集成,开发人员可以使用参数化查询轻松地在 SQL Server 之间移动数据,从而提高安全性并防止 SQL 注入。

最后,将 IronXL 和 Iron Software 添加到您的 .NET 开发工具集中,可以高效地操作 Excel、创建 PDF、进行 OCR 和使用条形码。 将 Iron Software 的灵活套件与 IronXL 的易用性、互操作性和性能相结合,可保证简化开发流程并提高应用程序功能。 凭借清晰的许可选项和可根据项目需求定制的方案,开发人员可以自信地选择合适的模式。 利用这些优势,开发人员可以有效地应对各种难题,同时保持合规性和开放性。

常见问题解答

用 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 机器人,将他对技术的热爱与创造力相结合。