如何在 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
- 設定開發環境
- 準備您的 Excel 文件
- 連線到您的 SQL Server 資料庫
- 使用 IronXL 從 Excel 檔案讀取數據
- 使用 IronPDF 匯出數據並產生 PDF 報告
- 查看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 - 按一下"新建"
- 從
Create a new project框的左側面板中,選擇您喜歡的程式語言-例如 C#。 - 從可用項目範本清單中選擇
Console App或Console App (.NET Core)範本。 - 在"名稱"區域,為你的專案取個名字。
如何在 C# 中將 Excel 檔案匯入 SQL Server:圖 3 - 提供名稱和儲存位置
- 確定項目保存位置。
- 按一下"建立"以啟動控制台應用程式專案。
安裝 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正在連線到 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將 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該類別負責使用 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結論
最後,在 .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 函式庫,您可以在不需要安裝 Microsoft Excel 的情況下,透過讀取 Excel 檔案並將資料插入資料庫,有效率地將 Excel 資料匯入 SQL Server。
不使用 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 檔案中的資料,並將其整合至應用程式中,而不會產生效能問題。
將 Excel 匯入 SQL Server 時,應該使用哪些錯誤處理策略?
實施 try-catch 區塊來處理潛在的錯誤,例如找不到檔案、資料格式無效或 SQL 異常,以確保匯入過程順利。
我可以在 C# 應用程式中自動匯入 Excel 資料到 SQL Server 嗎?
是的,使用 IronXL,您可以透過撰寫 C# 應用程式,讀取 Excel 檔案並將資料插入 SQL Server,以最少的手動介入,自動執行匯入程序。
參數化查詢如何防止 C# 中的 SQL injection?
C# 中的參數化查詢透過在 SQL 指令中使用參數占位符,可讓您安全地將資料插入 SQL Server,有助於防止 SQL 注入攻擊。
如何優化匯入 Excel 資料至 SQL Server 的效能?
透過使用批次插入、使用 IronXL 有效率地處理大型資料集,以及確保您的 SQL Server 連線和指令已正確設定,以最佳化效能。
在專案中使用 IronXL 有哪些授權選項?
IronXL 提供針對專案需求量身打造的彈性授權選項,讓開發人員可以選擇符合其應用需求與預算的最佳方案。









