跳至頁尾內容
使用 IRONXL
如何使用 IronXL 在 C# 中讀取 CSV 文件

C# 中讀取 CSV 檔案:教程

使用各種 Excel 格式通常需要讀取數據,然後以程式設計方式重新配置資料。 在本文中,我們將學習如何使用 IronXL(非常適合這項工作的工具)在 C# 中讀取 CSV 檔案並解析 Excel 電子表格中的資料。

什麼是CSV?

CSV 是一種簡單的資料格式,但可能存在許多差異; 在我們的 C# 專案中,以程式設計方式讀取資料可能很困難,因為它使用多個分隔符號來區分資料的行和列。 本文將向您展示如何使用IronXL 庫讀取 CSV 檔案。


1. 如何在 C# 中讀取 CSV 文件

在 MVC、ASP.NET 或 .NET Core 中使用 IronXL 讀取 CSV 檔案之前,您需要先安裝它。 以下是簡要介紹。

  1. 在 Visual Studio 中,選擇"專案"選單
  2. 管理 NuGet 套件
  3. 搜尋 IronXL.Excel
  4. 安裝

C# 讀取 CSV 檔案教學課程,圖 1:在 Visual Studio 的 NuGet 套件管理器中搜尋 IronXL 在 Visual Studio 的 NuGet 套件管理器中搜尋 IronXL

當您需要在 C# 中讀取 CSV 檔案時,IronXL 是完美的工具。 您可以讀取以逗號或其他任何分隔符號分隔的 CSV 文件,如下面的程式碼片段所示。

// Load a CSV file and interpret it as an Excel-like workbook
WorkBook workbook = WorkBook.LoadCSV("Weather.csv", fileFormat: ExcelFileFormat.XLSX, ListDelimiter: ",");

// Access the default worksheet in the workbook
WorkSheet ws = workbook.DefaultWorkSheet;

// Save the workbook to a new Excel file
workbook.SaveAs("Csv_To_Excel.xlsx");
// Load a CSV file and interpret it as an Excel-like workbook
WorkBook workbook = WorkBook.LoadCSV("Weather.csv", fileFormat: ExcelFileFormat.XLSX, ListDelimiter: ",");

// Access the default worksheet in the workbook
WorkSheet ws = workbook.DefaultWorkSheet;

// Save the workbook to a new Excel file
workbook.SaveAs("Csv_To_Excel.xlsx");
$vbLabelText   $csharpLabel

Output:

C# 中讀取 CSV 檔案:教程,圖 2:以逗號分隔符號輸出 CSV 文件 輸出以逗號分隔的 CSV 文件

代碼解釋:

創建了一個WorkBook物件。 然後使用 WorkBook 物件的LoadCSV方法來指定 CSV 的名稱、格式以及要讀取的 CSV 檔案中使用的分隔符號。 在這種情況下,逗號用作分隔符號。

然後創建一個WorkSheet物件。 這裡將放置 CSV 檔案的內容。 文件將以新名稱和新格式儲存。

C# 讀取 CSV 檔案教程,圖 3:資料在 Microsoft Excel 中顯示 資料以 Microsoft Excel 形式顯示


2. IronXL for Excel 文件

在您的專案中使用 IronXL,它是一種在 C# 中處理 Excel 檔案格式的簡化方法。 你可以透過直接下載的方式安裝 IronXL 。 或者,您可以使用適用於 Visual Studio 的 NuGet Install 。 該軟體可免費用於開發。

dotnet add package IronXL.Excel

3. 載入WorkBook並存取WorkSheet

WorkBook是 IronXL 的一個類,其物件提供對 Excel 檔案及其所有功能的完全存取權。 例如,如果我們想存取一個 Excel 文件,我們可以使用以下程式碼:

// Load the Excel file
WorkBook wb = WorkBook.Load("sample.xlsx"); // Excel file path
// Load the Excel file
WorkBook wb = WorkBook.Load("sample.xlsx"); // Excel file path
$vbLabelText   $csharpLabel

要存取 Excel 檔案的特定工作表,IronXL 提供了WorkSheet類別。

// Access a specific worksheet by name
WorkSheet ws = wb.GetWorkSheet("Sheet1"); // by sheet name
// Access a specific worksheet by name
WorkSheet ws = wb.GetWorkSheet("Sheet1"); // by sheet name
$vbLabelText   $csharpLabel

取得 Excel 工作表ws後,您可以從中提取任何類型的資料並對其執行所有 Excel 功能。 可以透過以下步驟從 Excel 工作表ws存取資料:

using IronXL;

class Program
{
    static void Main(string[] args)
    {
        // Load the workbook and access a specific worksheet
        WorkBook wb = WorkBook.Load("sample.xlsx");
        WorkSheet ws = wb.GetWorkSheet("Sheet1");

        // Iterate through a range of cells and display their values
        foreach (var cell in ws["A2:A10"])
        {
            Console.WriteLine("Value is: {0}", cell.Text);
        }
        Console.ReadKey();
    }
}
using IronXL;

class Program
{
    static void Main(string[] args)
    {
        // Load the workbook and access a specific worksheet
        WorkBook wb = WorkBook.Load("sample.xlsx");
        WorkSheet ws = wb.GetWorkSheet("Sheet1");

        // Iterate through a range of cells and display their values
        foreach (var cell in ws["A2:A10"])
        {
            Console.WriteLine("Value is: {0}", cell.Text);
        }
        Console.ReadKey();
    }
}
$vbLabelText   $csharpLabel

4. 將 Excel 工作表讀取為資料表

使用 IronXL,將 Excel WorkSheet作為資料表進行操作非常容易。

DataTable dt = ws.ToDataTable(true); // Converts the worksheet to a DataTable, using the first row as column names
DataTable dt = ws.ToDataTable(true); // Converts the worksheet to a DataTable, using the first row as column names
$vbLabelText   $csharpLabel

請使用以下命名空間:

using IronXL;
using System.Data;
using IronXL;
using System.Data;
$vbLabelText   $csharpLabel

編寫以下程式碼:

class Program
{
    static void Main(string[] args)
    {
        // Load the workbook and access a specific worksheet
        WorkBook wb = WorkBook.Load("Weather.xlsx"); // Your Excel file Name
        WorkSheet ws = wb.GetWorkSheet("Sheet1");

        // Parse worksheet into datatable
        DataTable dt = ws.ToDataTable(true); // Parse Sheet1 of sample.xlsx file into DataTable

        // Iterate through rows and columns to display their values
        foreach (DataRow row in dt.Rows) // Access rows
        {
            for (int i = 0; i < dt.Columns.Count; i++) // Access columns of corresponding row
            {
                Console.Write(row[i] + "  ");
            }
            Console.WriteLine();
        }
    }
}
class Program
{
    static void Main(string[] args)
    {
        // Load the workbook and access a specific worksheet
        WorkBook wb = WorkBook.Load("Weather.xlsx"); // Your Excel file Name
        WorkSheet ws = wb.GetWorkSheet("Sheet1");

        // Parse worksheet into datatable
        DataTable dt = ws.ToDataTable(true); // Parse Sheet1 of sample.xlsx file into DataTable

        // Iterate through rows and columns to display their values
        foreach (DataRow row in dt.Rows) // Access rows
        {
            for (int i = 0; i < dt.Columns.Count; i++) // Access columns of corresponding row
            {
                Console.Write(row[i] + "  ");
            }
            Console.WriteLine();
        }
    }
}
$vbLabelText   $csharpLabel

C# 中讀取 CSV 檔案:教程,圖 4:DataTable 物件的控制台輸出 來自 DataTable 物件的控制台輸出

在這個例子中,我們將了解如何使用 Excel 檔案作為DataSet

class Program
{
    static void Main(string[] args)
    {
        // Load the workbook and convert it to a DataSet
        WorkBook wb = WorkBook.Load("sample.xlsx");
        DataSet ds = wb.ToDataSet(); // Parse WorkBook wb into DataSet

        // Iterate through tables to display their names
        foreach (DataTable dt in ds.Tables)
        {
            Console.WriteLine(dt.TableName);
        }
    }
}
class Program
{
    static void Main(string[] args)
    {
        // Load the workbook and convert it to a DataSet
        WorkBook wb = WorkBook.Load("sample.xlsx");
        DataSet ds = wb.ToDataSet(); // Parse WorkBook wb into DataSet

        // Iterate through tables to display their names
        foreach (DataTable dt in ds.Tables)
        {
            Console.WriteLine(dt.TableName);
        }
    }
}
$vbLabelText   $csharpLabel

C# 中讀取 CSV 檔案:教程,圖 5:從 DataSet 物件存取工作表名稱 從資料集物件存取工作表名稱

讓我們來看另一個例子,了解如何存取所有 Excel 工作表中每個儲存格的值。 在這裡,我們可以存取 Excel 檔案中每個工作表的每個儲存格的值。

class Program
{
    static void Main(string[] args)
    {
        // Load the workbook and convert it to a DataSet
        WorkBook wb = WorkBook.Load("Weather.xlsx");
        DataSet ds = wb.ToDataSet(); // Treat the complete Excel file as DataSet

        // Iterate through each table and its rows and columns
        foreach (DataTable dt in ds.Tables) // Treat Excel WorkSheet as DataTable
        {
            foreach (DataRow row in dt.Rows) // Corresponding Sheet's Rows
            {
                for (int i = 0; i < dt.Columns.Count; i++) // Sheet columns of corresponding row
                {
                    Console.Write(row[i] + "  ");
                }
                Console.WriteLine();
            }
        }
    }
}
class Program
{
    static void Main(string[] args)
    {
        // Load the workbook and convert it to a DataSet
        WorkBook wb = WorkBook.Load("Weather.xlsx");
        DataSet ds = wb.ToDataSet(); // Treat the complete Excel file as DataSet

        // Iterate through each table and its rows and columns
        foreach (DataTable dt in ds.Tables) // Treat Excel WorkSheet as DataTable
        {
            foreach (DataRow row in dt.Rows) // Corresponding Sheet's Rows
            {
                for (int i = 0; i < dt.Columns.Count; i++) // Sheet columns of corresponding row
                {
                    Console.Write(row[i] + "  ");
                }
                Console.WriteLine();
            }
        }
    }
}
$vbLabelText   $csharpLabel

C# 中讀取 CSV 檔案:教程,圖 6:資料集物件的控制台輸出 資料集物件的控制台輸出

5. C# .NET 中的 CSV 解析

CSV 檔案在欄位中處理換行符的方式上有大量問題,或者欄位可能包含在引號中,從而完全阻止簡單的字串分割方法。 最近,我發現使用 C# .NET 轉換 CSV 時,可以透過指定可自訂的分隔符號而不是使用string.Split(&#39;,&#39;)以逗號分隔值,來實現以下選項。

6. 在 C# 記錄中讀取 CSV 數據

此過程會將讀取器切換到下一個檔案。我們在 TryGetField 中讀取 CSV 欄位檔案。 我們使用讀取函數將 CSV 檔案中的欄位作為記錄欄位。

// Load a CSV file, specify the file format and delimiter
WorkBook workbook = WorkBook.LoadCSV("Weather.csv", fileFormat: ExcelFileFormat.XLSX, ListDelimiter: ",");

// Access the default worksheet from the workbook
WorkSheet ws = workbook.DefaultWorkSheet;

// Convert worksheet to DataTable    
DataTable dt = ws.ToDataTable(true); // Parse Sheet1 of sample.xlsx file into DataTable

// Iterate through rows and columns to display their values
foreach (DataRow row in dt.Rows) // Access rows
{
    for (int i = 0; i < dt.Columns.Count; i++) // Access columns of corresponding row
    {
        Console.Write(row[i] + "  ");
    }
    Console.WriteLine();
}
// Load a CSV file, specify the file format and delimiter
WorkBook workbook = WorkBook.LoadCSV("Weather.csv", fileFormat: ExcelFileFormat.XLSX, ListDelimiter: ",");

// Access the default worksheet from the workbook
WorkSheet ws = workbook.DefaultWorkSheet;

// Convert worksheet to DataTable    
DataTable dt = ws.ToDataTable(true); // Parse Sheet1 of sample.xlsx file into DataTable

// Iterate through rows and columns to display their values
foreach (DataRow row in dt.Rows) // Access rows
{
    for (int i = 0; i < dt.Columns.Count; i++) // Access columns of corresponding row
    {
        Console.Write(row[i] + "  ");
    }
    Console.WriteLine();
}
$vbLabelText   $csharpLabel

C# 讀取 CSV 檔案教程,圖 7:DataTable 的控制台輸出 數據表的控制台輸出

7. 從 Excel 文件中取得數據

現在我們可以使用各種方法,輕鬆地從開啟的 Excel WorkSheet中取得任何類型的資料。 在以下範例中,我們可以看到如何存取特定單元格的值並將其解析為string

// Access the data by cell addressing
string val = ws["Cell Address"].ToString();
// Access the data by cell addressing
string val = ws["Cell Address"].ToString();
$vbLabelText   $csharpLabel

在上面的程式碼中, wsWorkSheet ,它是在步驟 2 中定義的。這是一種"簡單"的方法,但您可以閱讀更多內容並查看存取 Excel 文件資料的不同範例。

8. 如何在 C# 中解析 Excel 文件

在使用 Excel 電子表格進行應用程式建置時,我們經常需要根據資料分析結果,並且需要在 C# 中將 Excel 檔案資料解析為所需的格式才能獲得正確的結果。 在 C# 環境中,使用 IronXL 可以輕鬆地將資料解析成不同的格式; 請參閱以下步驟。

using IronXL;

class Program
{
    static void Main(string[] args)
    {
        // Load the workbook and access a specific worksheet
        WorkBook wb = WorkBook.Load("sample.xlsx");
        WorkSheet ws = wb.GetWorkSheet("Sheet1");

        // Parse Excel cell value into string
        string str_val = ws["B3"].Value.ToString();

        // Parse Excel cell value into Int32
        Int32 int32_val = ws["G3"].Int32Value;

        // Parse Excel cell value into Decimal
        decimal decimal_val = ws["E5"].DecimalValue;

        // Output parsed values to the console
        Console.WriteLine("Parse B3 Cell Value into String: {0}", str_val);
        Console.WriteLine("Parse G3 Cell Value into Int32: {0}", int32_val);
        Console.WriteLine("Parse E5 Cell Value into decimal: {0}", decimal_val);

        Console.ReadKey();
    }
}
using IronXL;

class Program
{
    static void Main(string[] args)
    {
        // Load the workbook and access a specific worksheet
        WorkBook wb = WorkBook.Load("sample.xlsx");
        WorkSheet ws = wb.GetWorkSheet("Sheet1");

        // Parse Excel cell value into string
        string str_val = ws["B3"].Value.ToString();

        // Parse Excel cell value into Int32
        Int32 int32_val = ws["G3"].Int32Value;

        // Parse Excel cell value into Decimal
        decimal decimal_val = ws["E5"].DecimalValue;

        // Output parsed values to the console
        Console.WriteLine("Parse B3 Cell Value into String: {0}", str_val);
        Console.WriteLine("Parse G3 Cell Value into Int32: {0}", int32_val);
        Console.WriteLine("Parse E5 Cell Value into decimal: {0}", decimal_val);

        Console.ReadKey();
    }
}
$vbLabelText   $csharpLabel

9. 如何將Excel資料解析為數值和布林值

現在我們來學習如何解析Excel檔案資料。 首先,讓我們來看看如何處理 Excel 中的數值數據,然後看看如何將其解析成我們所需的格式。

C# 中讀取 CSV 檔案:教程,圖 8:每種資料類型的總表 每種資料類型的總計表

class Program
{
    static void Main(string[] args)
    {
        // Load the workbook and access a specific worksheet
        WorkBook wb = WorkBook.Load("sample.xlsx");
        WorkSheet ws = wb.GetWorkSheet("Sheet1");

        // Parse Excel cell value into string
        string str_val = ws["B3"].Value.ToString();

        // Parse Excel cell value into Int32
        Int32 int32_val = ws["G3"].Int32Value;

        // Parse Excel cell value into Decimal
        decimal decimal_val = ws["E5"].DecimalValue;

        // Output parsed values to the console
        Console.WriteLine("Parse B3 Cell Value into String: {0}", str_val);
        Console.WriteLine("Parse G3 Cell Value into Int32: {0}", int32_val);
        Console.WriteLine("Parse E5 Cell Value into decimal: {0}", decimal_val);

        Console.ReadKey();
    }
}
class Program
{
    static void Main(string[] args)
    {
        // Load the workbook and access a specific worksheet
        WorkBook wb = WorkBook.Load("sample.xlsx");
        WorkSheet ws = wb.GetWorkSheet("Sheet1");

        // Parse Excel cell value into string
        string str_val = ws["B3"].Value.ToString();

        // Parse Excel cell value into Int32
        Int32 int32_val = ws["G3"].Int32Value;

        // Parse Excel cell value into Decimal
        decimal decimal_val = ws["E5"].DecimalValue;

        // Output parsed values to the console
        Console.WriteLine("Parse B3 Cell Value into String: {0}", str_val);
        Console.WriteLine("Parse G3 Cell Value into Int32: {0}", int32_val);
        Console.WriteLine("Parse E5 Cell Value into decimal: {0}", decimal_val);

        Console.ReadKey();
    }
}
$vbLabelText   $csharpLabel

這段程式碼將顯示以下輸出:

C# 中讀取 CSV 檔案:教程,圖 9:具有正確資料類型的控制台輸出 控制台輸出包含正確的資料類型

我們可以在這裡看到Excel檔案sample.xlsx的值:

C# 讀取 CSV 檔案教程,圖 10:在 Excel 中顯示正確的資料類型 在 Excel 中顯示正確的資料類型

IronXL 提供了BoolValue函數,用於將 Excel 檔案資料解析為布林資料類型。 它的用法如下:

// Access a cell value as a boolean
bool Val = ws["Cell Address"].BoolValue;
// Access a cell value as a boolean
bool Val = ws["Cell Address"].BoolValue;
$vbLabelText   $csharpLabel

10. 如何將 Excel 檔案解析為 C# 集合

class Program
{
    static void Main(string[] args)
    {
        // Load the workbook and access a specific worksheet
        WorkBook wb = WorkBook.Load("sample.xlsx");
        WorkSheet ws = wb.GetWorkSheet("Sheet1");

        // Convert a range into an array
        var array = ws["B6:F6"].ToArray();

        // Get the count of items in the array
        int item = array.Count();

        // Get the first item as a string
        string total_items = array[0].Value.ToString();

        // Output information about the array to the console
        Console.WriteLine("First item in the array: {0}", item);
        Console.WriteLine("Total items from B6 to F6: {0}", total_items);

        Console.ReadKey();
    }
}
class Program
{
    static void Main(string[] args)
    {
        // Load the workbook and access a specific worksheet
        WorkBook wb = WorkBook.Load("sample.xlsx");
        WorkSheet ws = wb.GetWorkSheet("Sheet1");

        // Convert a range into an array
        var array = ws["B6:F6"].ToArray();

        // Get the count of items in the array
        int item = array.Count();

        // Get the first item as a string
        string total_items = array[0].Value.ToString();

        // Output information about the array to the console
        Console.WriteLine("First item in the array: {0}", item);
        Console.WriteLine("Total items from B6 to F6: {0}", total_items);

        Console.ReadKey();
    }
}
$vbLabelText   $csharpLabel

10.1 如何將 Excel WorkSheet解析為資料表

IronXL 的一個出色功能是我們可以輕鬆地將特定的 Excel WorkSheet轉換為資料表。 為此,我們可以使用 IronXL 的.ToDataTable()函數,如下所示:

class Program
{
    static void Main(string[] args)
    {
        // Load the workbook and access a specific worksheet
        WorkBook wb = WorkBook.Load("sample.xlsx");
        WorkSheet ws = wb.GetWorkSheet("Sheet1");

        // Parse Sheet1 of sample.xlsx file into DataTable
        // Setting 'true' makes the first row in Excel as the column names in DataTable
        DataTable dt = ws.ToDataTable(true);
    }
}
class Program
{
    static void Main(string[] args)
    {
        // Load the workbook and access a specific worksheet
        WorkBook wb = WorkBook.Load("sample.xlsx");
        WorkSheet ws = wb.GetWorkSheet("Sheet1");

        // Parse Sheet1 of sample.xlsx file into DataTable
        // Setting 'true' makes the first row in Excel as the column names in DataTable
        DataTable dt = ws.ToDataTable(true);
    }
}
$vbLabelText   $csharpLabel

10.2 如何將 Excel 檔案解析為資料集

如果我們想要將完整的 Excel 檔案解析為 DataSet,那麼為此我們可以使用 IronXL 中的.ToDataSet()函數。

class Program
{
    static void Main(string[] args)
    {
        // Load an entire workbook into a DataSet
        WorkBook wb = WorkBook.Load("sample.xlsx");

        // Convert workbook to DataSet
        DataSet ds = wb.ToDataSet();

        // We can also get a DataTable from the DataSet which corresponds to a WorkSheet
        DataTable dt = ds.Tables[0];
    }
}
class Program
{
    static void Main(string[] args)
    {
        // Load an entire workbook into a DataSet
        WorkBook wb = WorkBook.Load("sample.xlsx");

        // Convert workbook to DataSet
        DataSet ds = wb.ToDataSet();

        // We can also get a DataTable from the DataSet which corresponds to a WorkSheet
        DataTable dt = ds.Tables[0];
    }
}
$vbLabelText   $csharpLabel

10.3 讀取特定範圍內的 Excel 數據

IronXL 提供了一種智慧方法來讀取特定範圍內的 Excel 檔案資料。 此範圍可以應用於行和列。

class Program
{
    static void Main(string[] args)
    {
        // Load the workbook and access a specific worksheet
        WorkBook wb = WorkBook.Load("sample.xlsx");
        WorkSheet ws = wb.GetWorkSheet("Sheet1");

        // Get specified range values by loop
        foreach (var item in ws["B3:B8"])
        {
            Console.WriteLine("Value is: {0}", item);
        }
        Console.ReadKey();
    }
}
class Program
{
    static void Main(string[] args)
    {
        // Load the workbook and access a specific worksheet
        WorkBook wb = WorkBook.Load("sample.xlsx");
        WorkSheet ws = wb.GetWorkSheet("Sheet1");

        // Get specified range values by loop
        foreach (var item in ws["B3:B8"])
        {
            Console.WriteLine("Value is: {0}", item);
        }
        Console.ReadKey();
    }
}
$vbLabelText   $csharpLabel

上述程式碼顯示以下輸出:

C# 讀取 CSV 檔案教學,圖 11:控制台輸出,存取 B3:B8 範圍內的所有值 控制台輸出以存取 B3:B8 範圍內的所有值

並產生 Excel 檔案 sample.xlsx 中的值:

C# 讀取 CSV 檔案教學,圖 12:範例檔案 sample.xlsx 的資料展示 範例檔案 sample.xlsx 的資料展示

此外,IronXL 還相容於許多 Excel 方法,可用於與儲存格交互,包括樣式和邊框數學函數條件格式或根據可用資料建立圖表。

11. 如何讀取 Excel 檔案中的布林數據

在應用程式開發中,我們需要根據 Excel 文件中的布林資料類型做出決策。

class Program
{
    static void Main(string[] args)
    {
        // Load the workbook and access a specific worksheet
        WorkBook wb = WorkBook.Load("sample.xlsx");
        WorkSheet ws = wb.GetWorkSheet("Sheet1");

        // Traverse a range and output boolean values
        foreach (var item in ws["G1:G10"])
        {
            Console.WriteLine("Condition is: {0}", item.BoolValue);
        }
        Console.ReadKey();
    }
}
class Program
{
    static void Main(string[] args)
    {
        // Load the workbook and access a specific worksheet
        WorkBook wb = WorkBook.Load("sample.xlsx");
        WorkSheet ws = wb.GetWorkSheet("Sheet1");

        // Traverse a range and output boolean values
        foreach (var item in ws["G1:G10"])
        {
            Console.WriteLine("Condition is: {0}", item.BoolValue);
        }
        Console.ReadKey();
    }
}
$vbLabelText   $csharpLabel

由此,我們得到以下輸出:

C# 讀取 CSV 檔案教程,圖 13:取得布林資料的控制台輸出 取得布林資料時的控制台輸出

Excel 檔案 sample.xlsx,其中包含 C1 到 C10 的值:

C# 中讀取 CSV 檔案:教程,圖 14:Excel 範例,可與控制台輸出進行比較 用於與控制台輸出進行比較的 Excel 範例

12. 如何閱讀完整的Excel工作表

利用行和列索引可以輕鬆讀取完整的 Excel 工作表。 為此,我們使用兩個循環:一個用於遍歷所有行,另一個用於遍歷特定行的所有列。 這樣我們就可以輕鬆取得整個 Excel 工作表中所有儲存格的值。

class Program
{
    static void Main(string[] args)
    {
        // Load the workbook and access a specific worksheet
        WorkBook wb = WorkBook.Load("Weather.xlsx"); // Your Excel File Name
        WorkSheet ws = wb.GetWorkSheet("Sheet1");

        // Traverse all rows of Excel WorkSheet
        for (int i = 0; i < ws.Rows.Count(); i++)
        {
            // Traverse all columns of specific Row
            for (int j = 0; j < ws.Columns.Count(); j++)
            {
                // Get the values
                string val = ws.Rows[i].Columns[j].Value.ToString();
                Console.WriteLine("Value of Row {0} and Column {1} is: {2}", i, j, val);
            }
        }
        Console.ReadKey();
    }
}
class Program
{
    static void Main(string[] args)
    {
        // Load the workbook and access a specific worksheet
        WorkBook wb = WorkBook.Load("Weather.xlsx"); // Your Excel File Name
        WorkSheet ws = wb.GetWorkSheet("Sheet1");

        // Traverse all rows of Excel WorkSheet
        for (int i = 0; i < ws.Rows.Count(); i++)
        {
            // Traverse all columns of specific Row
            for (int j = 0; j < ws.Columns.Count(); j++)
            {
                // Get the values
                string val = ws.Rows[i].Columns[j].Value.ToString();
                Console.WriteLine("Value of Row {0} and Column {1} is: {2}", i, j, val);
            }
        }
        Console.ReadKey();
    }
}
$vbLabelText   $csharpLabel

C# 中讀取 CSV 檔案:教程,圖 15:讀取所有值後的控制台輸出 讀取所有值的控制台輸出

13. 如何在不使用互通的情況下讀取 Excel 文件

IronXL 是一個適用於 C# 和 .NET 的 Excel 程式庫,它允許開發人員無需使用 Microsoft.Office.Interop.Excel 即可XLS 和 XLSX文件讀取和編輯 Excel 資料。

該 API 使我們能夠直觀地創建、讀取、操作、保存和匯出 Excel 文件,用於:

  1. .NET Framework 4.5+
  2. .NET Core 2+
  3. .NET 標準
  4. Xamarin
  5. Windows Mobile
  6. 單聲道
  7. 和 Azure 雲端託管
  8. Blazor
  9. .NET 版本

新增下列名稱空間:

using IronXL;
using System;
using System.Linq;
using IronXL;
using System;
using System.Linq;
$vbLabelText   $csharpLabel

現在在主函數中編寫以下程式碼。

class Program
{
    static void Main(string[] args)
    {
        // Load an Excel file and access the first worksheet
        WorkBook workbook = WorkBook.Load("Weather.xlsx");
        WorkSheet sheet = workbook.WorkSheets.First();

        // Select cells easily in Excel notation and return the calculated value
        int cellValue = sheet["A2"].IntValue;

        // Read from ranges of cells elegantly
        foreach (var cell in sheet["A2:A10"])
        {
            Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text);
        }
    }
}
class Program
{
    static void Main(string[] args)
    {
        // Load an Excel file and access the first worksheet
        WorkBook workbook = WorkBook.Load("Weather.xlsx");
        WorkSheet sheet = workbook.WorkSheets.First();

        // Select cells easily in Excel notation and return the calculated value
        int cellValue = sheet["A2"].IntValue;

        // Read from ranges of cells elegantly
        foreach (var cell in sheet["A2:A10"])
        {
            Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text);
        }
    }
}
$vbLabelText   $csharpLabel

C# 讀取 CSV 檔案教程,圖 16:每個單元格的控制台輸出 每個單元格的控制台輸出

IronXL 也完全支援 ASP.NET、MVC、Windows、macOS、Linux、iOS 和 Android 行動應用程式開發。

14. 結論和 Iron XL 特別優惠

除了在 C# 中解析 CSV 檔案外,IronXL 只需兩行程式碼即可將 CSV 檔案轉換為 Excel 檔案!

使用 C# 或 VB.NET,無需互通即可輕鬆使用 IronXL 的 Excel API。您可以讀取、編輯和建立 Excel 電子表格,或處理其他 Excel 格式,例如XLS/XLSX/CSV/TSV 。 透過多種框架的支持,您可以花兩件產品的價格購買五件產品。 點擊我們的定價頁面以了解更多資訊。

C# 中讀取 CSV 檔案:教程,圖 17:Iron Suite 的 5 個產品 Iron Suite 的 5 款產品

常見問題解答

如何在C#中讀取CSV檔?

要在 C# 中讀取 CSV 文件,可以使用 IronXL 庫。只需在 Visual Studio 中透過 NuGet 安裝程式庫即可。安裝完成後,使用WorkBook.LoadCSV方法載入並解析 CSV 檔案。

什麼是 CSV 檔案?為什麼在 C# 中處理 CSV 檔案會比較複雜?

CSV 是一種簡單的資料格式,但由於分隔符號種類繁多,處理起來可能很複雜。 IronXL 簡化了在 C# 專案中讀取和解析 CSV 檔案的過程。

我可以使用 C# 將 CSV 檔案轉換為 Excel 檔案嗎?

是的,IronXL 允許您透過載入 CSV 檔案並使用WorkBook.SaveAs方法儲存,將 CSV 檔案轉換為 Excel 格式,例如 XLS 或 XLSX。

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

您可以使用 Visual Studio 中的 NuGet 套件管理器安裝 IronXL。搜尋「IronXL.Excel」並將其新增至您的專案中,即可開始處理 Excel 檔案。

是否可以在 C# 中將 Excel 儲存格資料解析為特定資料型別?

是的,使用 IronXL,您可以使用Int32ValueBoolValue等方法將 Excel 單元格值解析為特定資料類型,例如數值和布林值。

如何使用 C# 讀取 Excel 表格中特定儲存格區域的資料?

使用 IronXL,您可以透過循環遍歷範圍並利用 IronXL 的索引功能存取儲存格值,從而讀取特定儲存格中的資料。

如何在 C# 中將 Excel 工作表轉換為 DataTable?

您可以使用 IronXL 的WorkSheet.ToDataTable方法將 Excel 工作表轉換為 DataTable,該方法可以有效地將工作表解析為 DataTable 物件以進行資料操作。

我是否需要 Microsoft Office Interop 才能以程式設計方式讀取 Excel 檔案?

不,使用 IronXL,您可以讀取和操作 Excel 檔案而無需 Microsoft Office Interop,使其成為一個獨立且高效的解決方案。

使用 IronXL 處理 Excel 和 CSV 檔案有哪些優勢?

IronXL 安裝簡便,無需依賴 Interop,支援多種 Excel 格式,並相容於各種 .NET 框架,從而提高了處理 CSV 和 Excel 檔案的工作效率。

如何在 C# 中讀取完整的 Excel 工作表?

若要使用 IronXL 讀取完整的 Excel 工作表,可以使用巢狀循環遍歷所有行和列,並使用 IronXL 的方法提取儲存格值。

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