跳至頁尾內容
使用 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;
    }
}
$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();
            }
        }
    }
}
$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.");
    }
}
$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);
}
$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,方法是讀取 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,您可以透過編寫 C# 應用程式來自動執行匯入過程,該應用程式可以讀取 Excel 檔案並將資料插入 SQL Server,只需極少的人工幹預。

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

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

如何最佳化將 Excel 資料匯入 SQL Server 的效能?

透過使用批次插入、使用 IronXL 高效處理大型資料集以及確保 SQL Server 連接和命令配置正確來優化效能。

在專案中使用 IronXL 有哪些授權選項?

IronXL 提供靈活的許可選項,可根據專案需求量身定制,使開發人員能夠選擇最符合其應用程式要求和預算的方案。

喬迪·巴迪亞
軟體工程師
喬迪精通Python、C#和C++,除了在Iron Software運用這些技能外,他還從事遊戲程式設計。他參與產品測試、產品開發和研究等工作,為產品的持續改進做出了巨大貢獻。豐富的經驗讓他始終保持挑戰性和工作熱情,他表示這是他最喜歡在Iron Software工作的原因之一。喬迪在佛羅裡達州邁阿密長大,畢業於佛羅裡達大學,主修電腦科學和統計學。