跳過到頁腳內容
使用 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 文件的處理。 這個強大的工具非常適合服務器端應用程式,因為它使得開發人員無需在電腦上安裝 Microsoft Excel 就能讀取、創建和編輯 Excel 文件。 IronXL 支援 Excel 2007 及以後版本 (.xlsx) 和 Excel 97–2003 (.xls) 格式,提供了管理不同 Excel 文件版本的靈活性。 它允許進行重要的數據操作,例如操作工作表、行和列以及插入、更新和刪除數據。

IronXL 還支持單元格格式化和 Excel 公式,從而實現複雜且格式良好的電子表格的程式生成。 憑藉其性能優化和與多個 .NET 平臺的兼容性,包括 .NET Framework、.NET Core 和 .NET 5/6,IronXL 保證有效處理大數據集。 對於希望將 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. 開始一個新項目:選擇 文件 -> 新建 -> 項目

如何在 C# 中將 Excel 導入到 SQL Server:圖 2 - 點擊新建

  1. 創建新項目框的左側面板中,選擇您偏好的編程語言,例如 C#。
  2. 從可用的項目範本列表中選擇控制台應用程序控制台應用程序 (.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 函數加載 Excel 工作簿,打開第一個工作表,通過循環瀏覽數據工作表的行來收集數據。 為了便於表格處理,信息存儲在字典列表中。

如何在 C# 中將 Excel 導入到 SQL Server:圖 7 - 示例輸入 Excel 文件

此類將數據插入到指定的資料庫表中,並負責與 SQL Server 資料庫的連接。 InsertData 方法使用參數化查詢防止 SQL 注入,並根據字典的鍵(代表列名)動態構建 SQL 插入查詢。

使用 ExcelReader 類將數據從 Excel 文件讀入 SQL 表,使用 SqlServerConnector 類將每一行插入到 SQL Server 表中,Main 函數管理整個過程。

如何在 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

結論

最後,使用 C# 和 IronXL 將數據從 Excel 導入到 MS SQL 資料庫中,是管理 .NET 應用程式內 Excel 文件的有效且可靠的方法。 IronXL 與多種 Excel 格式兼容,並具有強大的功能,使讀取和寫入 Excel 數據變得更容易,而無需安裝 Microsoft Excel。 通過將 System.Data.SqlClient 與 IronXL 集成,開發人員可以輕鬆地在 SQL Servers 之間移動數據,使用參數化查詢提高安全性並防止 SQL 注入。

最後,將 IronXL 和 Iron Software 添加到您的 .NET 開發工具集中,使您能夠高效處理 Excel、創建 PDF、進行 OCR 和利用條形碼。 結合使用 Iron Software 的靈活套件與 IronXL 的易用性、互操作性和性能,確保了簡化的開發流程和改進的應用程式能力。 通過明確的許可選項,量身定制為滿足項目需求,開發人員可以自信地選擇合適的模型。 通過利用這些優勢,開發者可以高效解決一系列困境,同時保持合規性和透明性。

常見問題解答

使用 C# 將 Excel 數據匯入 SQL Server 的最佳方法是什麼?

使用 IronXL 庫,您可以通過讀取 Excel 文件並將數據插入數據庫,高效地將 Excel 數據匯入 SQL Server,而不需要安裝 Microsoft Excel。

如何在 C# 中不使用 Microsoft Excel 讀取 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 提供靈活的許可選項,根據項目需求量身定制,使開發人員能夠選擇最符合其應用程序需求和預算的計劃。

Jordi Bardia
軟體工程師
Jordi 在 Python、C# 和 C++ 上最得心應手,當他不在 Iron Software 展現技術時,便在做遊戲編程。在分担产品测测试,产品开发和研究的责任时,Jordi 为持续的产品改进增值。他说这种多样化的经验使他受到挑战并保持参与, 而这也是他与 Iron Software 中工作一大乐趣。Jordi 在佛罗里达州迈阿密长大,曾在佛罗里达大学学习计算机科学和统计学。