跳至頁尾內容
USING IRONXL
如何從CSV檔案讀取資料並使用C#將其儲存到資料庫中

如何從 CSV 文件讀取資料並將其儲存到資料庫 C# 中

在當今的數位世界中,有效地處理資料是一項重要的任務。 軟體開發中的一個常見需求是從CSV文件中讀取資料並將其儲存在資料庫中。 本教程涵蓋了使用C#從CSV文件讀取資料並使用IronXL程式庫將其儲存在SQL Server資料庫中的步驟。 本指南是為初學者設計的,將以簡單、有趣的方式解釋。

了解基礎知識

什麼是CSV文件?

CSV(逗號分隔值)文件是一種純文字文件,其中包含以逗號分隔的資料。 由於其簡單性和與各種應用程式(如Excel)的相容性,它是一種流行的資料傳輸格式。

SQL Server的角色和資料庫

SQL Server是微軟的資料庫管理系統。 它用於以結構化方式儲存和管理資料。 在我們的案例中,我們將把CSV資料儲存在SQL Server的表中。

IronXL簡介

IronXL是專為.NET應用程式量身定制的Excel程式庫,專門設計用於讓開發人員在不需要Microsoft Office Interop的情況下讀取、產生和編輯Excel文件。該程式庫以其與各種.NET版本和平台(包括.NET Core、.NET Standard和.NET Framework)以及支持不同操作系統(如Windows、Linux和macOS)的相容性而脫穎而出。 這是一個強大的資料匯入程式庫,尤其是在處理CSV文件時。

How to Read and Store Data From CSV Files in C

  1. 在Visual Studio中建立一個C#控制台程式。
  2. 使用NuGet包管理器安裝CSV程式庫。
  3. 使用程式庫在程式中載入CSV文件。
  4. 與資料庫建立連接。
  5. 使用程式庫從CSV文件中讀取內容。
  6. 使用SqlBulkCopy方法將該內容複製到資料庫中。

這裡有一個範例程式碼片段:

using System;
using System.Data;
using System.Data.SqlClient; // For .NET Core/.NET 5+, use Microsoft.Data.SqlClient instead
using System.Globalization;
using System.IO;
using CsvHelper;

namespace CsvReader
{
    class Program
    {
        static void Main(string[] args)
        {
            string csvPath = @"path\to\your\csv\file.csv";

            using (var reader = new StreamReader(csvPath))
            using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
            {
                // Mapping the CSV data to the corresponding model
                var records = csv.GetRecords<YourModel>();

                using (var sqlBulkCopy = new SqlBulkCopy("your_connection_string"))
                {
                    sqlBulkCopy.DestinationTableName = "YourTableName";
                    sqlBulkCopy.WriteToServer(records.AsDataReader());
                }

                Console.WriteLine("Data imported successfully!");
            }
        }
    }

    // Define your model that maps to the CSV columns
    public class YourModel
    {
        // Define properties here representing the CSV columns
    }
}
using System;
using System.Data;
using System.Data.SqlClient; // For .NET Core/.NET 5+, use Microsoft.Data.SqlClient instead
using System.Globalization;
using System.IO;
using CsvHelper;

namespace CsvReader
{
    class Program
    {
        static void Main(string[] args)
        {
            string csvPath = @"path\to\your\csv\file.csv";

            using (var reader = new StreamReader(csvPath))
            using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
            {
                // Mapping the CSV data to the corresponding model
                var records = csv.GetRecords<YourModel>();

                using (var sqlBulkCopy = new SqlBulkCopy("your_connection_string"))
                {
                    sqlBulkCopy.DestinationTableName = "YourTableName";
                    sqlBulkCopy.WriteToServer(records.AsDataReader());
                }

                Console.WriteLine("Data imported successfully!");
            }
        }
    }

    // Define your model that maps to the CSV columns
    public class YourModel
    {
        // Define properties here representing the CSV columns
    }
}
Imports System
Imports System.Data
Imports System.Data.SqlClient ' For .NET Core/.NET 5+, use Microsoft.Data.SqlClient instead
Imports System.Globalization
Imports System.IO
Imports CsvHelper

Namespace CsvReader
    Class Program
        Shared Sub Main(args As String())
            Dim csvPath As String = "path\to\your\csv\file.csv"

            Using reader As New StreamReader(csvPath)
                Using csv As New CsvReader(reader, CultureInfo.InvariantCulture)
                    ' Mapping the CSV data to the corresponding model
                    Dim records = csv.GetRecords(Of YourModel)()

                    Using sqlBulkCopy As New SqlBulkCopy("your_connection_string")
                        sqlBulkCopy.DestinationTableName = "YourTableName"
                        sqlBulkCopy.WriteToServer(records.AsDataReader())
                    End Using

                    Console.WriteLine("Data imported successfully!")
                End Using
            End Using
        End Sub
    End Class

    ' Define your model that maps to the CSV columns
    Public Class YourModel
        ' Define properties here representing the CSV columns
    End Class
End Namespace
$vbLabelText   $csharpLabel

確保將"YourTableName"替換為您的資料庫表的名稱。

設置環境

前提條件

  1. Visual Studio:確保您已經安裝了Visual Studio。
  2. SQL Server:您應該已經安裝並可以存取SQL Server。
  3. IronXL安裝:通過運行以下NuGet命令安裝IronXL:
dotnet add package IronXL.Excel

確保在您要安裝IronXL的專案目錄內運行這些命令。

建立SQL Server表

在匯入資料前,請在您的SQL Server資料庫中建立一個目標表。 該表將儲存CSV資料。

CREATE TABLE YourTableName (
    Column1 DataType,
    Column2 DataType,
    ...
);

用您的具體資訊替換DataType

CSV資料匯入步驟指南

  1. 首先,確保您有一個包含您要匯入資料的CSV文件。
  2. 在Visual Studio中建立一個新的C#控制台應用程式專案。
  3. 安裝CsvHelper NuGet封包以讀取CSV文件。 您可以通過打開Visual Studio中的NuGet包管理控制台並運行以下命令來完成此操作:

    Install-Package CsvHelper
    Install-Package CsvHelper
    SHELL
  4. 在C#程式碼文件的開頭新增所需的using語句:

    using System;
    using System.IO;
    using System.Globalization;
    using CsvHelper;
    using System.Data.SqlClient; // For .NET Core/.NET 5+, use Microsoft.Data.SqlClient instead
    using System;
    using System.IO;
    using System.Globalization;
    using CsvHelper;
    using System.Data.SqlClient; // For .NET Core/.NET 5+, use Microsoft.Data.SqlClient instead
    Imports System
    Imports System.IO
    Imports System.Globalization
    Imports CsvHelper
    Imports System.Data.SqlClient ' For .NET Core/.NET 5+, use Microsoft.Data.SqlClient instead
    $vbLabelText   $csharpLabel
  5. 在程式碼中指定您的CSV文件的路徑。例如:

    string csvFilePath = @"C:\path\to\your\csv\file.csv";
    string csvFilePath = @"C:\path\to\your\csv\file.csv";
    Dim csvFilePath As String = "C:\path\to\your\csv\file.csv"
    $vbLabelText   $csharpLabel

    確保將C:\path\to\your\csv\file.csv替換為您的CSV文件的實際路徑。

  6. 建立StreamReader類的新實例以讀取CSV文件:

    using (var reader = new StreamReader(csvFilePath))
    {
        // code goes here
    }
    using (var reader = new StreamReader(csvFilePath))
    {
        // code goes here
    }
    Using reader = New StreamReader(csvFilePath)
    	' code goes here
    End Using
    $vbLabelText   $csharpLabel
  7. 建立StreamReader物件:

    using (var reader = new StreamReader(csvFilePath))
    using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
    {
        // code goes here
    }
    using (var reader = new StreamReader(csvFilePath))
    using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
    {
        // code goes here
    }
    Using reader = New StreamReader(csvFilePath)
    Using csv = New CsvReader(reader, CultureInfo.InvariantCulture)
    	' code goes here
    End Using
    End Using
    $vbLabelText   $csharpLabel
  8. 可選,通過將CsvReader以進行任何必要的設置。 例如:

    var config = new CsvConfiguration(CultureInfo.InvariantCulture)
    {
        HasHeaderRecord = true,
    };
    using var csv = new CsvReader(reader, config);
    var config = new CsvConfiguration(CultureInfo.InvariantCulture)
    {
        HasHeaderRecord = true,
    };
    using var csv = new CsvReader(reader, config);
    Imports System.Globalization
    Imports CsvHelper
    
    Dim config As New CsvConfiguration(CultureInfo.InvariantCulture) With {
        .HasHeaderRecord = True
    }
    
    Using csv As New CsvReader(reader, config)
        ' Use csv here
    End Using
    $vbLabelText   $csharpLabel
  9. 使用GetRecords<t>()方法將CSV資料讀取到一個物件集合中。 用表示CSV文件中每個記錄的物件型別替換<t>。例如:

    var records = csv.GetRecords<YourModel>();
    var records = csv.GetRecords<YourModel>();
    Dim records = csv.GetRecords(Of YourModel)()
    $vbLabelText   $csharpLabel

    確保將YourModel替換為您的模型類的實際名稱。

  10. 迭代記錄並執行任何所需的處理或驗證:

    foreach (var record in records)
    {
        // Process each record as needed
    }
    foreach (var record in records)
    {
        // Process each record as needed
    }
    For Each record In records
    	' Process each record as needed
    Next record
    $vbLabelText   $csharpLabel
  11. 選擇性地,使用ADO.NET或像Entity Framework這樣的ORM工具建立與SQL Server資料庫的連接。
  12. 使用您選擇的資料庫存取機制將每個記錄插入資料庫中。 例如,如果您使用ADO.NET,您可以利用SqlBulkCopy類來有效地批量插入資料。
  13. 在導入過程中,處理可能發生的任何異常並提供適當的錯誤資訊或日誌。
  14. 通過運行應用程式並驗證CSV資料是否成功導入到資料庫中來測試您的應用程式。

就是這樣! 您現在已經成功將CSV資料匯入到您的SQL Server資料庫中,使用C#。

步驟1:讀取CSV文件

當開始從CSV文件導入資料時,第一個關鍵步驟是準確地讀取其中的資料。 CSV文件中的每行通常代表一個資料記錄,每個記錄由一個或多個以逗號分隔的字段組成。

然後,我們使用IronXL程式庫來處理CSV文件。要使用IronXL讀取CSV文件,您將使用其WorkSheet類。 WorkBook物件中時,IronXL將CSV文件視為一個試算表/資料表。

using IronXL;
using System.Data;

public class CSVReader
{
    // Reads a CSV file and converts it to a DataTable
    public DataTable ReadCSV(string filePath)
    {
        WorkBook workbook = WorkBook.Load(filePath);
        WorkSheet sheet = workbook.DefaultWorkSheet;
        // Convert to DataTable for easier processing
        DataTable dataTable = sheet.ToDataTable(true); // Set to 'true' if your CSV has a header row
        return dataTable;
    }
}
using IronXL;
using System.Data;

public class CSVReader
{
    // Reads a CSV file and converts it to a DataTable
    public DataTable ReadCSV(string filePath)
    {
        WorkBook workbook = WorkBook.Load(filePath);
        WorkSheet sheet = workbook.DefaultWorkSheet;
        // Convert to DataTable for easier processing
        DataTable dataTable = sheet.ToDataTable(true); // Set to 'true' if your CSV has a header row
        return dataTable;
    }
}
Imports IronXL
Imports System.Data

Public Class CSVReader
	' Reads a CSV file and converts it to a DataTable
	Public Function ReadCSV(ByVal filePath As String) As DataTable
		Dim workbook As WorkBook = WorkBook.Load(filePath)
		Dim sheet As WorkSheet = workbook.DefaultWorkSheet
		' Convert to DataTable for easier processing
		Dim dataTable As DataTable = sheet.ToDataTable(True) ' Set to 'true' if your CSV has a header row
		Return dataTable
	End Function
End Class
$vbLabelText   $csharpLabel

步驟2:建立資料庫連接

建立與SQL Server資料庫的連接是在資料庫中儲存CSV資料過程中的一個基本步驟。 這一步涉及在您的應用程式和資料庫伺服器之間建立通信鏈路。 成功的連接至關重要,因為沒有它,將資料轉移到資料庫是不可能的。

這一步重點放在使用C#中的連接字串建立和開啟連接。 連接字串是一個關鍵組件,因為它包含建立連接所需的資訊。 它就像打開您資料庫門的鑰匙。

using System.Data.SqlClient; // For .NET Core/.NET 5+, use Microsoft.Data.SqlClient instead

public class DatabaseConnector
{
    // Connection string to connect to the database
    private string connectionString = "your_connection_string_here";

    public SqlConnection ConnectToDatabase()
    {
        SqlConnection connection = new SqlConnection(connectionString);
        connection.Open();
        return connection;
    }
}
using System.Data.SqlClient; // For .NET Core/.NET 5+, use Microsoft.Data.SqlClient instead

public class DatabaseConnector
{
    // Connection string to connect to the database
    private string connectionString = "your_connection_string_here";

    public SqlConnection ConnectToDatabase()
    {
        SqlConnection connection = new SqlConnection(connectionString);
        connection.Open();
        return connection;
    }
}
Imports System.Data.SqlClient ' For .NET Core/.NET 5+, use Microsoft.Data.SqlClient instead

Public Class DatabaseConnector
    ' Connection string to connect to the database
    Private connectionString As String = "your_connection_string_here"

    Public Function ConnectToDatabase() As SqlConnection
        Dim connection As New SqlConnection(connectionString)
        connection.Open()
        Return connection
    End Function
End Class
$vbLabelText   $csharpLabel

connectionString變數包含連接SQL Server所需的所有細節。 它通常包括伺服器名稱、資料庫名稱、使用者ID和密碼。 一個範例連接字串如下所示:Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;。 確保將這些佔位符替換為您的實際伺服器詳細資訊。

步驟3:將資料儲存在資料庫中

在與SQL Server資料庫建立連接後,下一個關鍵步驟是在資料庫中儲存CSV資料。 這一步涉及將您已讀取和處理的資料轉移到SQL Server表中。 這是資料處理過程中的一個關鍵部分,因為它涉及從本地文件到資料庫伺服器的實際資料遷移。

在這一步中,我們將重點放在如何將現在儲存在DataTable中的CSV資料轉移到SQL Server資料庫中。 我們使用C#和SQL Server功能的組合,來高效地完成這項任務。

using System;
using System.Data;
using System.Data.SqlClient; // For .NET Core/.NET 5+, use Microsoft.Data.SqlClient instead

public class DataImporter
{
    public void ImportData(DataTable dataTable)
    {
        using (SqlConnection connection = new DatabaseConnector().ConnectToDatabase())
        {
            // Check if the table exists and create it if it does not.
            string tableName = "CSVData"; // Use a valid SQL table name format
            string checkTable = $"IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = '{tableName}') BEGIN ";
            string createTable = "CREATE TABLE " + tableName + " (";
            for (int i = 0; i < dataTable.Columns.Count; i++)
            {
                createTable += $"[{dataTable.Columns[i].ColumnName}] NVARCHAR(MAX)";
                if (i < dataTable.Columns.Count - 1)
                    createTable += ", ";
            }
            createTable += ") END";
            SqlCommand createTableCommand = new SqlCommand(checkTable + createTable, connection);
            createTableCommand.ExecuteNonQuery();

            // Now we use SqlBulkCopy to import the data
            using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connection))
            {
                bulkCopy.DestinationTableName = tableName;
                try
                {
                    bulkCopy.WriteToServer(dataTable);
                    Console.WriteLine("Data imported successfully!");
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
        }
    }
}
using System;
using System.Data;
using System.Data.SqlClient; // For .NET Core/.NET 5+, use Microsoft.Data.SqlClient instead

public class DataImporter
{
    public void ImportData(DataTable dataTable)
    {
        using (SqlConnection connection = new DatabaseConnector().ConnectToDatabase())
        {
            // Check if the table exists and create it if it does not.
            string tableName = "CSVData"; // Use a valid SQL table name format
            string checkTable = $"IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = '{tableName}') BEGIN ";
            string createTable = "CREATE TABLE " + tableName + " (";
            for (int i = 0; i < dataTable.Columns.Count; i++)
            {
                createTable += $"[{dataTable.Columns[i].ColumnName}] NVARCHAR(MAX)";
                if (i < dataTable.Columns.Count - 1)
                    createTable += ", ";
            }
            createTable += ") END";
            SqlCommand createTableCommand = new SqlCommand(checkTable + createTable, connection);
            createTableCommand.ExecuteNonQuery();

            // Now we use SqlBulkCopy to import the data
            using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connection))
            {
                bulkCopy.DestinationTableName = tableName;
                try
                {
                    bulkCopy.WriteToServer(dataTable);
                    Console.WriteLine("Data imported successfully!");
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
        }
    }
}
Imports System
Imports System.Data
Imports System.Data.SqlClient ' For .NET Core/.NET 5+, use Microsoft.Data.SqlClient instead

Public Class DataImporter
    Public Sub ImportData(dataTable As DataTable)
        Using connection As SqlConnection = New DatabaseConnector().ConnectToDatabase()
            ' Check if the table exists and create it if it does not.
            Dim tableName As String = "CSVData" ' Use a valid SQL table name format
            Dim checkTable As String = $"IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = '{tableName}') BEGIN "
            Dim createTable As String = "CREATE TABLE " & tableName & " ("
            For i As Integer = 0 To dataTable.Columns.Count - 1
                createTable &= $"[{dataTable.Columns(i).ColumnName}] NVARCHAR(MAX)"
                If i < dataTable.Columns.Count - 1 Then
                    createTable &= ", "
                End If
            Next
            createTable &= ") END"
            Dim createTableCommand As New SqlCommand(checkTable & createTable, connection)
            createTableCommand.ExecuteNonQuery()

            ' Now we use SqlBulkCopy to import the data
            Using bulkCopy As New SqlBulkCopy(connection)
                bulkCopy.DestinationTableName = tableName
                Try
                    bulkCopy.WriteToServer(dataTable)
                    Console.WriteLine("Data imported successfully!")
                Catch ex As Exception
                    Console.WriteLine(ex.Message)
                End Try
            End Using
        End Using
    End Sub
End Class
$vbLabelText   $csharpLabel

首先,使用DatabaseConnector類打開與SQL Server資料庫的連接,確保資料傳輸以順利進行。 方法會檢查資料庫中名為"CSVData"的表是否存在。

如果未找到該表,則開始建立它。 表的架構基於傳遞到方法的NVARCHAR(MAX)以適應任何文字資料。 這是一般性的做法,可能需要進一步細化,以更緊密地符合特定資料型別。

之後,制定和執行SQL命令,驗證表是否存在或建立它。 這可以確保後續的批量複製操作有一個準備好的目標表進行資料插入。 表準備好後,使用DataTable直接轉輸到SQL Server表中。 此操作專為高效能的批量資料傳輸設計,非常適合處理大量資料。

步驟4:整合所有步驟

在認真完成了前面的讀取CSV資料、建立資料庫連接和準備資料傳輸後,我們進入最後也是關鍵階段:將這些單獨的組件整合為一個連貫的過程。

此整合是在C#應用程式的Main方法中進行的,在這裡一切融會貫通,實現從CSV文件到SQL Server資料庫的實際資料匯入。

class Program
{
    static void Main(string[] args)
    {
        string filePath = "path_to_your_csv_file.csv";
        CSVReader reader = new CSVReader();
        DataTable dataTable = reader.ReadCSV(filePath);
        DataImporter importer = new DataImporter();
        importer.ImportData(dataTable);
        Console.WriteLine("Data imported successfully!");
    }
}
class Program
{
    static void Main(string[] args)
    {
        string filePath = "path_to_your_csv_file.csv";
        CSVReader reader = new CSVReader();
        DataTable dataTable = reader.ReadCSV(filePath);
        DataImporter importer = new DataImporter();
        importer.ImportData(dataTable);
        Console.WriteLine("Data imported successfully!");
    }
}
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim filePath As String = "path_to_your_csv_file.csv"
		Dim reader As New CSVReader()
		Dim dataTable As DataTable = reader.ReadCSV(filePath)
		Dim importer As New DataImporter()
		importer.ImportData(dataTable)
		Console.WriteLine("Data imported successfully!")
	End Sub
End Class
$vbLabelText   $csharpLabel

用您的CSV文件路徑替換path_to_your_csv_file.csv

運行專案

專案運行後,您將看到以下輸出。 成功的消息表明所有操作已成功執行,並且資料已複製到資料庫中。

Data imported successfully!

現在,您可以打開SQL Server Management Studio (SSMS),檢查資料庫下的表。 您將在表中看到以下資料。

如何從CSV文件讀取資料並將其儲存在資料庫中C#:圖1-輸出資料庫

結論

本教程指導您通過使用C#從CSV文件讀取資料並將其儲存到SQL Server資料庫的過程。 通過遵循這些步驟並使用IronXL程式庫,您可以在C#應用程式中高效管理CSV資料。

IronXL提供免費試用,允許使用者在購買前體驗其功能。 這個功能完備的試用版允許潛在使用者在無水印的生產環境中測試和評估產品。 在試用期結束後,如果您決定繼續在您的專案中使用IronXL,產品的授權從$999開始。

常見問題

如何在C#中從CSV檔案讀取資料?

您可以使用IronXL程式庫在C#中從CSV檔案讀取資料。IronXL提供了`WorkBook`和`WorkSheet`類,使您可以將CSV檔案當作Excel試算表來載入和操作。

使用C#將CSV資料儲存在SQL Server資料庫中的步驟是什麼?

要在C#中使用SQL Server資料庫儲存CSV資料,首先使用IronXL讀取CSV,然後將資料載入到`DataTable`中,並使用`SqlBulkCopy`將資料高效地插入到SQL Server表中。

如何在我的C#專案中安裝IronXL?

您可以使用Visual Studio中的NuGet套件管理器在您的C#專案中安裝IronXL。在NuGet套件管理器中搜尋'IronXL'並將其新增到您的專案。

使用IronXL處理C#中的CSV檔案的主要優勢是什麼?

使用IronXL處理C#中的CSV檔案的主要優勢是它能夠在.NET應用程式中無縫管理和操作CSV和Excel檔案,提供跨各種.NET版本和作業系統的相容性。

我可以使用IronXL處理Excel檔案和CSV檔案嗎?

可以,IronXL旨在處理Excel和CSV檔案,使其成為在.NET應用程式中管理試算表資料的多功能工具。

如果我在使用IronXL讀取CSV檔案時遇到錯誤,應該怎麼辦?

如果您在使用IronXL讀取CSV檔案時遇到錯誤,請確保該CSV檔案格式正確且IronXL正確安裝在您的專案中。您可以參考IronXL的文件以獲取疑難解答提示。

在購買前我如何測試IronXL的功能?

IronXL提供了一個完整功能的免費試用版,允許您在生產環境中無任何限制地測試和評估該產品。

使用IronXL將CSV資料儲存在資料庫中的前提條件是什麼?

前提條件包括安裝Visual Studio、存取SQL Server和透過NuGet安裝IronXL。您還需設置一個SQL Server表來儲存CSV資料。

Curtis Chau
技術作家

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

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

Iron 支援團隊

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