跳至頁尾內容
USING 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程式庫

How to Import Excel to SQL Server in C

  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保證能有效處理大型資料集。 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. 開始一個新專案:選擇File -> New -> Project

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

  1. Create a new project框的左面板中選擇您偏好的程式語言,例如C#。
  2. 從可用專案模板列表中選擇Console 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命名空間建立與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 INSERT查詢。

使用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

結論

最後,將資料從Excel匯入MS SQL資料庫,使用C#和IronXL,是管理.NET應用中Excel文件的有效和可靠方法。 IronXL支援多種Excel格式,強大的功能使讀取和書寫Excel資料更簡單,而無需安裝Microsoft Excel。 通過与IronXL整合System.Data.SqlClient,開發者可以輕鬆地通過參數化查詢在SQL Server之間移動資料,以提高安全性並防止SQL注入。

最後,將IronXL和Iron Software新增到您的.NET開發工具組中,讓您可以高效操控Excel、建立PDF、進行OCR及使用條碼。 結合Iron Software的靈活套件與IronXL的使用簡便性、互操作性和性能保證了精簡的開發和提升的應用能力。 擁有明確的授權選項,可以根據專案的需求進行定制,開發人員可以自信地選擇合適的模式。 藉由利用這些優勢,開發者可以有效地解決一系列的挑戰,同時保持合規性和透明度。

常見問題

using C# 將 Excel 資料匯入 SQL Server 的最佳方法是什麼?

using IronXL 程式庫,您可以高效地將 Excel 資料匯入 SQL Server,通過讀取 Excel 文件並將資料插入資料庫中而不需要安裝 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,您可以通過編寫讀取 Excel 文件並將資料插入 SQL Server 的 C# 應用程式,來最小化手動干預,從而自動化匯入過程。

參數化查詢如何在 C# 中防止 SQL 注入?

C# 中的參數化查詢允許您通過在 SQL 指令中使用參數佔位符安全地將資料插入 SQL Server,這有助於防止 SQL 注入攻擊。

如何優化將 Excel 資料匯入 SQL Server 的性能?

通過使用批量插入、高效處理大型資料集并確保 SQL Server 連接和指令正確配置來優化性能。

在項目中使用 IronXL 的授權選項有哪些?

IronXL 提供符合項目需求的靈活授權選項,使開發者能夠根據應用程式需求和預算選擇最佳方案。

Curtis Chau
技術作家

Curtis Chau擁有Carleton大學的電腦科學學士學位,專精於前端開發,擁有Node.js、TypeScript、JavaScript和React的專業知識。Curtis熱衷於建立直觀且美觀的使用者介面,喜愛使用現代框架並建立結構良好、視覺吸引力的手冊。

除了開發,Curtis對物聯網(IoT)有濃厚的興趣,探索創新的方法來整合硬體和軟體。在空閒時間,他喜歡玩遊戲和建立Discord機器人,結合他對技術的熱愛與創造力。

Iron 支援團隊

我們線上24小時,每週5天。
聊天
電子郵件
給我打電話