フッターコンテンツにスキップ
IRONXLの使用
C#でIronXLを使用してCSVファイルを読む方法

C#でCSVファイルを読み取る: チュートリアル

さまざまなExcel形式を扱う場合、データを読み取り、それをプログラムで再構成する必要があることがよくあります。 この記事では、IronXLを使用してC#でCSVファイルを読み取り、Excelスプレッドシートからデータを解析する方法を学びます。IronXLはこの作業に最適なツールです。

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");
' Load a CSV file and interpret it as an Excel-like workbook
Dim workbook As WorkBook = WorkBook.LoadCSV("Weather.csv", fileFormat:= ExcelFileFormat.XLSX, ListDelimiter:= ",")

' Access the default worksheet in the workbook
Dim ws As WorkSheet = workbook.DefaultWorkSheet

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

出力:

C#でCSVファイルを読み取る: チュートリアル、図2: カンマ区切りのCSVファイルを出力 カンマ区切りのCSVファイルを出力

  1. IronWordのライセンスキーを指定するために、IronWord.License.LicenseKey("YOUR-LICENSE-KEY"を実際のキーに置き換えます)を設定します。

WorkBookオブジェクトが作成されます。 次に、WorkBookオブジェクトのLoadCSVメソッドを使用してCSVの名前、形式、読み取り中のCSVファイルで使用されている区切り文字を指定します。 この場合、区切り文字としてカンマが使用されています。

WorkSheetオブジェクトが作成されます。 ここにCSVファイルの内容が配置されます。 ファイルは新しい名前と形式で保存されます。

C#でCSVファイルを読み取る: チュートリアル、図3: Microsoft Excelに表示されるデータ Microsoft Excelに表示されるデータ


2. IronXL for Excel Files

IronXLを使用すると、C#でExcelファイル形式をスムーズに操作できます。 直接ダウンロードでIronXLをインストールすることもできます。 または、Visual StudioのNuGetインストールを使用することもできます。 ソフトウェアは開発用には無料です。

dotnet add package IronXL.Excel

3. WorkBookをロードしWorkSheetにアクセスする

WorkBookは、Excelファイルとそのすべての機能へのフルアクセスを提供するIronXLのクラスです。 例えば、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
' Load the Excel file
Dim wb As WorkBook = 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
' Access a specific worksheet by name
Dim ws As WorkSheet = 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();
    }
}
Imports IronXL

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Load the workbook and access a specific worksheet
		Dim wb As WorkBook = WorkBook.Load("sample.xlsx")
		Dim ws As WorkSheet = wb.GetWorkSheet("Sheet1")

		' Iterate through a range of cells and display their values
		For Each cell In ws("A2:A10")
			Console.WriteLine("Value is: {0}", cell.Text)
		Next cell
		Console.ReadKey()
	End Sub
End Class
$vbLabelText   $csharpLabel

4. Excel WorkSheetをDataTableとして読み取る

IronXLを使用すると、Excel WorkSheetをDataTableとして非常に簡単に操作できます。

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
Dim dt As DataTable = 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;
Imports IronXL
Imports 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();
        }
    }
}
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Load the workbook and access a specific worksheet
		Dim wb As WorkBook = WorkBook.Load("Weather.xlsx") ' Your Excel file Name
		Dim ws As WorkSheet = wb.GetWorkSheet("Sheet1")

		' Parse worksheet into datatable
		Dim dt As DataTable = ws.ToDataTable(True) ' Parse Sheet1 of sample.xlsx file into DataTable

		' Iterate through rows and columns to display their values
		For Each row As DataRow In dt.Rows ' Access rows
			For i As Integer = 0 To dt.Columns.Count - 1 ' Access columns of corresponding row
				Console.Write(row(i) & "  ")
			Next i
			Console.WriteLine()
		Next row
	End Sub
End Class
$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);
        }
    }
}
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Load the workbook and convert it to a DataSet
		Dim wb As WorkBook = WorkBook.Load("sample.xlsx")
		Dim ds As DataSet = wb.ToDataSet() ' Parse WorkBook wb into DataSet

		' Iterate through tables to display their names
		For Each dt As DataTable In ds.Tables
			Console.WriteLine(dt.TableName)
		Next dt
	End Sub
End Class
$vbLabelText   $csharpLabel

C#でCSVファイルを読み取る: チュートリアル、図5: DataSetオブジェクトからシート名を取得 DataSetオブジェクトからシート名を取得

すべてのExcelシートの各セル値にアクセスする別の例を見てみましょう。 ここでは、ExcelファイルのすべてのWorkSheetの各セル値にアクセスできます。

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();
            }
        }
    }
}
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Load the workbook and convert it to a DataSet
		Dim wb As WorkBook = WorkBook.Load("Weather.xlsx")
		Dim ds As DataSet = wb.ToDataSet() ' Treat the complete Excel file as DataSet

		' Iterate through each table and its rows and columns
		For Each dt As DataTable In ds.Tables ' Treat Excel WorkSheet as DataTable
			For Each row As DataRow In dt.Rows ' Corresponding Sheet's Rows
				For i As Integer = 0 To dt.Columns.Count - 1 ' Sheet columns of corresponding row
					Console.Write(row(i) & "  ")
				Next i
				Console.WriteLine()
			Next row
		Next dt
	End Sub
End Class
$vbLabelText   $csharpLabel

C#でCSVファイルを読み取る: チュートリアル、図6: Datasetオブジェクトのコンソール出力 Datasetオブジェクトのコンソール出力

5. C# .NETでのCSV解析

CSVファイルは、フィールド内の改行の処理方法や、単純な文字列分割アプローチで完全にブロックされるかもしれない引用符で囲まれたフィールドなど、問題が豊富です。 C# .NETでCSVを変換する際に、カスタマイズ可能な区切り文字を指定することで、コンマ区切りのstring.Split(',')を使用して値を分割する代わりに、次のオプションを最近見つけました。

6. C# Recordsでの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();
}
' Load a CSV file, specify the file format and delimiter
Dim workbook As WorkBook = WorkBook.LoadCSV("Weather.csv", fileFormat:= ExcelFileFormat.XLSX, ListDelimiter:= ",")

' Access the default worksheet from the workbook
Dim ws As WorkSheet = workbook.DefaultWorkSheet

' Convert worksheet to DataTable    
Dim dt As DataTable = ws.ToDataTable(True) ' Parse Sheet1 of sample.xlsx file into DataTable

' Iterate through rows and columns to display their values
For Each row As DataRow In dt.Rows ' Access rows
	For i As Integer = 0 To dt.Columns.Count - 1 ' Access columns of corresponding row
		Console.Write(row(i) & "  ")
	Next i
	Console.WriteLine()
Next row
$vbLabelText   $csharpLabel

C#でCSVファイルを読み取る: チュートリアル、図7: DataTableからのコンソール出力 DataTableからのコンソール出力

7. Excelファイルからデータを取得する

これで、開いたExcelWorkSheetからさまざまなメソッドを使用して、あらゆる種類のデータを簡単に取得できます。 次の例では、特定のセル値にアクセスし、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();
' Access the data by cell addressing
Dim val As String = ws("Cell Address").ToString()
$vbLabelText   $csharpLabel

上記の行で、wsは第2ステップで定義されたWorkSheetです。これは 'シンプルな' アプローチですが、もっと読むことでExcelファイルのデータにアクセスするさまざまな方法を見ることができます。

8. C#でExcelファイルを解析する方法

アプリケーションビルドにExcelスプレッドシートを使用する場合、データに基づいて結果を分析することがよくあり、C#内でExcelファイルデータを必要な形式に解析して正しい結果を得る必要があります。 IronXLを使用すると、C#環境での異なる形式へのデータの解析が簡単になります; 以下の手順を参照してください。

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();
    }
}
Imports IronXL

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Load the workbook and access a specific worksheet
		Dim wb As WorkBook = WorkBook.Load("sample.xlsx")
		Dim ws As WorkSheet = wb.GetWorkSheet("Sheet1")

		' Parse Excel cell value into string
		Dim str_val As String = ws("B3").Value.ToString()

		' Parse Excel cell value into Int32
		Dim int32_val As Int32 = ws("G3").Int32Value

		' Parse Excel cell value into Decimal
		Dim decimal_val As Decimal = 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()
	End Sub
End Class
$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();
    }
}
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Load the workbook and access a specific worksheet
		Dim wb As WorkBook = WorkBook.Load("sample.xlsx")
		Dim ws As WorkSheet = wb.GetWorkSheet("Sheet1")

		' Parse Excel cell value into string
		Dim str_val As String = ws("B3").Value.ToString()

		' Parse Excel cell value into Int32
		Dim int32_val As Int32 = ws("G3").Int32Value

		' Parse Excel cell value into Decimal
		Dim decimal_val As Decimal = 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()
	End Sub
End Class
$vbLabelText   $csharpLabel

このコードは次の出力を表示します:

C#でCSVファイルを読み取る: チュートリアル、図9: 正しいデータ型のコンソール出力 正しいデータ型のコンソール出力

ここでExcelファイルsample.xlsxの値を見ることができます:

C#でCSVファイルを読み取る: チュートリアル、図10: Excelに正しいデータ型を表示 Excelに正しいデータ型を表示

Excelファイルデータをブールデータ型に解析するには、IronXLはBoolValue関数を提供します。 次のように使用できます。

// 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;
' Access a cell value as a boolean
Dim Val As Boolean = 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();
    }
}
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Load the workbook and access a specific worksheet
		Dim wb As WorkBook = WorkBook.Load("sample.xlsx")
		Dim ws As WorkSheet = wb.GetWorkSheet("Sheet1")

		' Convert a range into an array
		Dim array = ws("B6:F6").ToArray()

		' Get the count of items in the array
		Dim item As Integer = array.Count()

		' Get the first item as a string
		Dim total_items As String = 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()
	End Sub
End Class
$vbLabelText   $csharpLabel

10.1 ExcelWorkSheetをDataTableに解析する方法

IronXLの優れた機能の1つは、特定のExcelWorkSheetをDataTableに簡単に変換できることです。 この目的のために、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);
    }
}
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Load the workbook and access a specific worksheet
		Dim wb As WorkBook = WorkBook.Load("sample.xlsx")
		Dim ws As WorkSheet = 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
		Dim dt As DataTable = ws.ToDataTable(True)
	End Sub
End Class
$vbLabelText   $csharpLabel

10.2 ExcelファイルをDataSetに解析する方法

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];
    }
}
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Load an entire workbook into a DataSet
		Dim wb As WorkBook = WorkBook.Load("sample.xlsx")

		' Convert workbook to DataSet
		Dim ds As DataSet = wb.ToDataSet()

		' We can also get a DataTable from the DataSet which corresponds to a WorkSheet
		Dim dt As DataTable = ds.Tables(0)
	End Sub
End Class
$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();
    }
}
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Load the workbook and access a specific worksheet
		Dim wb As WorkBook = WorkBook.Load("sample.xlsx")
		Dim ws As WorkSheet = wb.GetWorkSheet("Sheet1")

		' Get specified range values by loop
		For Each item In ws("B3:B8")
			Console.WriteLine("Value is: {0}", item)
		Next item
		Console.ReadKey()
	End Sub
End Class
$vbLabelText   $csharpLabel

上記のコードは次の出力を表示します:

C#でCSVファイルを読み取る: チュートリアル、図11: 範囲B3:B8内のすべての値にアクセスするコンソール出力 範囲B3:B8内のすべての値にアクセスするコンソール出力

そしてExcelファイルsample.xlsxの値を生成します:

C#でCSVファイルを読み取る: チュートリアル、図12: sample.xlsxからのデータ表示 sample.xlsxからのデータ表示

Additionally, IronXL is also compatible with many Excel methods to interact with cells including styling and border, math functions, conditional formatting or creating charts from available data.

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();
    }
}
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Load the workbook and access a specific worksheet
		Dim wb As WorkBook = WorkBook.Load("sample.xlsx")
		Dim ws As WorkSheet = wb.GetWorkSheet("Sheet1")

		' Traverse a range and output boolean values
		For Each item In ws("G1:G10")
			Console.WriteLine("Condition is: {0}", item.BoolValue)
		Next item
		Console.ReadKey()
	End Sub
End Class
$vbLabelText   $csharpLabel

これにより、次の出力が得られます:

C#でCSVファイルを読み取る: チュートリアル、図13: ブールデータの取得からのコンソール出力 ブールデータの取得からのコンソール出力

そして、Excelファイルsample.xlsxのC1からC10の値:

C#でCSVファイルを読み取る: チュートリアル、図14: コンソール出力と比較するためのExcelサンプル コンソール出力と比較するためのExcelサンプル

12. 完全なExcel WorkSheetを読み取る方法

行と列のインデックスを使用して、完全なExcel WorkSheetを読み取るのは簡単です。 この目的のために、1つのループで全行を横断し、もう1つで特定の行のすべての列を横断します。 その後、Excel WorkSheet全体のすべてのセル値を簡単に取得できます。

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();
    }
}
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Load the workbook and access a specific worksheet
		Dim wb As WorkBook = WorkBook.Load("Weather.xlsx") ' Your Excel File Name
		Dim ws As WorkSheet = wb.GetWorkSheet("Sheet1")

		' Traverse all rows of Excel WorkSheet
		For i As Integer = 0 To ws.Rows.Count() - 1
			' Traverse all columns of specific Row
			For j As Integer = 0 To ws.Columns.Count() - 1
				' Get the values
				Dim val As String = ws.Rows(i).Columns(j).Value.ToString()
				Console.WriteLine("Value of Row {0} and Column {1} is: {2}", i, j, val)
			Next j
		Next i
		Console.ReadKey()
	End Sub
End Class
$vbLabelText   $csharpLabel

C#でCSVファイルを読み取る: チュートリアル、図15: すべての値を読み取るコンソール出力 すべての値を読み取るコンソール出力

13. InteropなしでExcelファイルを読み取る方法

IronXLは、開発者がXLSおよびXLSX文書からExcelデータを読み取り、編集できるようにするC#向けのExcelライブラリであり、Microsoft.Office.Interop.Excelを使用せずに行います。

このAPIは、次のためにExcelファイルを直感的に作成、読み取り、操作、保存、エクスポートできるようにします:

  1. .NET Framework 4.5+
  2. .NET Core 2+
  3. .NET Standard
  4. Xamarin
  5. Windowsモバイル
  6. Mono
  7. & Azureクラウドホスティング
  8. Blazor
  9. .NET MAUI

次の名前空間を追加します。

using IronXL;
using System;
using System.Linq;
using IronXL;
using System;
using System.Linq;
Imports IronXL
Imports System
Imports 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);
        }
    }
}
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Load an Excel file and access the first worksheet
		Dim workbook As WorkBook = WorkBook.Load("Weather.xlsx")
		Dim sheet As WorkSheet = workbook.WorkSheets.First()

		' Select cells easily in Excel notation and return the calculated value
		Dim cellValue As Integer = sheet("A2").IntValue

		' Read from ranges of cells elegantly
		For Each cell In sheet("A2:A10")
			Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text)
		Next cell
	End Sub
End Class
$vbLabelText   $csharpLabel

C#でCSVファイルを読み取る: チュートリアル、図16: 各セルのコンソール出力 各セルのコンソール出力

IronXLは、ASP.NET、MVC、Windows、macOS、Linux、iOS、およびAndroidモバイルアプリケーション開発も完全にサポートしています。

14. 結論とIron XLスペシャルオファー

C#でのCSV解析に加えて、IronXLはCSVファイルをわずか2行のコードでExcelに変換します!

C#またはVB.NETを使用すると、Interopを使用せずにIronXLのExcel APIを非常に簡単に使用できます。Excelスプレッドシートを読み取り、編集、作成したり、XLS/XLSX/CSV/TSVなどの他のExcel形式で操作したりできます。 複数のフレームワークをサポートしているため、2つの価格で5つの製品を購入できます。 価格ページをクリックして詳細情報を確認してください。

C#でCSVファイルを読み取る: チュートリアル、図17: Iron Suiteの5つの製品 Iron Suiteの5つの製品

よくある質問

C#でCSVファイルを読むことができますか?

C# で CSV ファイルを読み取るには、NuGet を介して Visual Studio にライブラリをインストールして IronXL を使用できます。 インストール後、WorkBook.LoadCSV メソッドを使用して CSV ファイルを読み込み、解釈します。

CSV とは何であり、なぜ C# で扱うのが複雑な場合があるのですか?

CSV はシンプルなデータ形式ですが、区切り文字が異なるため、扱いが複雑になる可能性があります。IronXL は C# プロジェクトで CSV ファイルの読み取りと解析を簡素化します。

C# を使用して CSV ファイルを Excel に変換できますか?

はい、IronXL を使用すると、CSV を読み込んで WorkBook.SaveAs メソッドで保存することで、CSV ファイルを XLS または XLSX 形式の Excel に変換できます。

C#プロジェクトにIronXLをどのようにインストールしますか?

Visual Studio の NuGet パッケージ マネージャーを使用して IronXL をインストールできます。 'IronXL.Excel' を検索してプロジェクトに追加し、Excel ファイルの操作を開始します。

Excel セル データを C# で特定のデータ型に解析することは可能ですか?

はい、IronXL を使用すると、Int32ValueBoolValue などのメソッドを使用して、Excel セルの値を数値型や Boolean 型などの特定のデータ型に解析できます。

C# を使用して Excel シートの特定のセル範囲からデータを読み取るにはどうすればよいですか?

IronXL を使用すると、ループを使用して範囲を反復処理し、IronXL のインデックス機能を介してセルの値にアクセスすることで、特定のセルからデータを読み取ることができます。

C# で Excel ワークシートを DataTable に変換するにはどうすればよいですか?

IronXL の WorkSheet.ToDataTable メソッドを使用すると、ワークシートを効率的に解析して DataTable オブジェクトに変換し、データ操作を容易にします。

プログラムで Excel ファイルを読み取るために Microsoft Office Interop が必要ですか?

いいえ、IronXL を使用すると、Microsoft Office Interop を使用せずに Excel ファイルを読み取り、操作できます。これにより、単独で効率的なソリューションになります。

Excel および CSV ファイルの操作に IronXL を使用する利点は何ですか?

IronXL は簡単なインストール、Interop への依存なし、複数の Excel 形式のサポート、およびさまざまな .NET フレームワークとの互換性を提供し、CSV および Excel ファイルの処理における生産性を向上させます。

C# で完全な Excel ワークシートを読み取るにはどうすればよいですか?

IronXL を使用して Excel ワークシートを完全に読み取るには、ネストされたループを使用してすべての行と列をトラバースし、IronXL のメソッドを使用してセル値を抽出します。

Curtis Chau
テクニカルライター

Curtis Chauは、カールトン大学でコンピュータサイエンスの学士号を取得し、Node.js、TypeScript、JavaScript、およびReactに精通したフロントエンド開発を専門としています。直感的で美しいユーザーインターフェースを作成することに情熱を持ち、Curtisは現代のフレームワークを用いた開発や、構造の良い視覚的に魅力的なマニュアルの作成を楽しんでいます。

開発以外にも、CurtisはIoT(Internet of Things)への強い関心を持ち、ハードウェアとソフトウェアの統合方法を模索しています。余暇には、ゲームをしたりDiscordボットを作成したりして、技術に対する愛情と創造性を組み合わせています。