Zum Fußzeileninhalt springen
IRONXL VERWENDEN
Wie man CSV-Dateien in C# mit IronXL liest

CSV-Dateien in C#: ein Tutorial lesen

Das Arbeiten mit verschiedenen Excel-Formaten erfordert oft das Einlesen von Daten und deren anschließende programmatische Umstrukturierung. In diesem Artikel werden wir lernen, wie man eine CSV-Datei liest und Daten aus einer Excel-Tabelle in C# mit IronXL, dem perfekten Werkzeug für diesen Job, analysiert.

Was ist CSV?

CSV ist ein einfaches Datenformat, aber es kann viele Unterschiede geben; es kann in unseren C#-Projekten schwierig zu programmatisch zu lesen sein, da es mehrere Trennzeichen zur Unterscheidung zwischen Zeilen und Spalten von Daten verwendet. Dieser Artikel zeigt Ihnen, wie Sie die IronXL-Bibliothek verwenden, um CSV-Dateien zu lesen.


1. Wie liest man eine CSV-Datei in C#?

Bevor Sie IronXL verwenden können, um CSV-Dateien in MVC, ASP.NET oder .NET Core zu lesen, müssen Sie es installieren. Hier ist eine kurze Anleitung.

  1. Wählen Sie im Visual Studio das Menü Projekt
  2. Verwalten Sie NuGet-Pakete
  3. Suchen Sie nach IronXL.Excel
  4. Installieren

CSV-Dateien in C# lesen: Ein Tutorial, Abbildung 1: Suche nach IronXL im NuGet-Paket-Manager in Visual Studio Suche nach IronXL im NuGet-Paket-Manager in Visual Studio

Wenn Sie CSV-Dateien in C# lesen müssen, ist IronXL das perfekte Werkzeug. Sie können eine CSV-Datei mit Kommas oder jedem anderen Trennzeichen lesen, wie in den folgenden Code-Segmenten zu sehen ist.

// 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

Ausgabe:

CSV-Dateien in C# lesen: Ein Tutorial, Abbildung 2: CSV-Datei mit Komma-Trennzeichen ausgeben CSV-Datei mit Komma-Trennzeichen ausgeben

Code-Erklärung:

Ein WorkBook-Objekt wird erstellt. Die LoadCSV-Methode für das WorkBook-Objekt wird dann verwendet, um den Namen der CSV, ihr Format und die Trennzeichen anzugeben, die in der gelesenen CSV-Datei verwendet werden. In diesem Fall werden Kommas als Trennzeichen verwendet.

Ein WorkSheet-Objekt wird dann erstellt. Hier werden die Inhalte der CSV-Datei abgelegt. Die Datei wird unter einem neuen Namen und Format gespeichert.

CSV-Dateien in C# lesen: Ein Tutorial, Abbildung 3: Daten in Microsoft Excel angezeigt Daten in Microsoft Excel angezeigt


2. IronXL für Excel-Dateien

Verwenden Sie IronXL für Ihr Projekt als optimierte Methode zum Arbeiten mit Excel-Dateiformaten in C#. Sie können entweder IronXL über direkten Download installieren. Alternativ können Sie NuGet Install für Visual Studio verwenden. Die Software ist kostenlos für die Entwicklung.

dotnet add package IronXL.Excel

3. WorkBook laden und WorkSheet zugreifen

WorkBook ist die Klasse von IronXL, deren Objekt vollständigen Zugriff auf die Excel-Datei und alle ihre Funktionen bietet. Zum Beispiel, wenn wir auf eine Excel-Datei zugreifen möchten, würden wir den Code verwenden:

// 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

Um auf das spezifische Arbeitsblatt einer Excel-Datei zuzugreifen, bietet IronXL die WorkSheet-Klasse.

// 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

Sobald Sie das Excel-Arbeitsblatt ws erhalten haben, können Sie jeden Datentyp daraus extrahieren und alle Excel-Funktionen darauf ausführen. Daten können aus dem Excel-Arbeitsblatt ws durch diesen Prozess abgerufen werden:

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. Ein Excel-WorkSheet als DataTable lesen

Mit IronXL ist es sehr einfach, mit einem Excel-WorkSheet als DataTable zu arbeiten.

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

Verwenden Sie die folgenden Namensräume:

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

Schreiben Sie den folgenden Code:

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

CSV-Dateien in C# lesen: Ein Tutorial, Abbildung 4: Konsolenausgabe von einem DataTable-Objekt Konsolenausgabe von einem DataTable-Objekt

In diesem Beispiel werden wir sehen, wie man eine Excel-Datei als DataSet verwendet.

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

CSV-Dateien in C# lesen: Ein Tutorial, Abbildung 5: Blattname aus DataSet-Objekt abrufen Blattname aus DataSet-Objekt abrufen

Schauen wir uns ein weiteres Beispiel an, wie man auf jeden Zellwert über alle Excel-Blätter zugreift. Hier können wir auf jeden Zellwert jedes WorkSheets in einer Excel-Datei zugreifen.

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

CSV-Dateien in C# lesen: Ein Tutorial, Abbildung 6: Konsolenausgabe vom Dataset-Objekt Konsolenausgabe vom Dataset-Objekt

5. CSV-Parsing in C# .NET

CSV-Dateien haben zahlreiche Probleme mit der Behandlung von Zeilenumbrüchen in Feldern oder wie Felder in Anführungszeichen sein können, die einen einfachen String-Split-Ansatz völlig blockieren. Ich habe kürzlich die folgenden Optionen entdeckt, um CSV in C# .NET zu konvertieren, indem ein anpassbares Trennzeichen angegeben wird, anstatt string.Split(',') zu verwenden, um die Werte in einem Komma zu trennen.

6. CSV-Daten in C# Records lesen

Dieser Prozess schreitet den Leser durch die nächste Datei fort. Wir lesen die CSV-Felddateien in TryGetField. Wir verwenden die Lese-Funktion auf Feldfeldern der CSV-Dateien als Datensatzfelder.

// 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

CSV-Dateien in C# lesen: Ein Tutorial, Abbildung 7: Konsolenausgabe von DataTable Konsolenausgabe von DataTable

7. Daten aus Excel-Dateien abrufen

Jetzt können wir auf einfache Weise jeden Datentyp mit verschiedenen Methoden aus dem geöffneten Excel-WorkSheet abrufen. Im folgenden Beispiel sehen wir, wie man auf einen bestimmten Zellwert zugreift und ihn in string analysiert:

// 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

In der obigen Zeile ist ws das WorkSheet, das in Schritt 2 definiert wurde. Dies ist 'der einfache' Ansatz, aber Sie können mehr lesen und verschiedene Beispiele sehen, wie auf Excel-Dateidaten zugegriffen wird.

8. Wie man Excel-Dateien in C# analysiert

Bei der Verwendung von Excel-Tabellen für den Applikationsaufbau analysieren wir oft die Ergebnisse basierend auf Daten und müssen Excel-Dateidaten innerhalb von C# in das erforderliche Format analysieren, um die richtigen Ergebnisse zu erzielen. Das Analysieren von Daten in verschiedene Formate wird in der C#-Umgebung mit der Verwendung von IronXL vereinfacht; siehe die folgenden Schritte.

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-Daten in numerische & boolesche Werte analysieren

Jetzt gehen wir dazu über, wie man Excel-Dateidaten analysiert. Zuerst schauen wir uns an, wie man mit numerischen Excel-Daten umgeht und dann, wie man sie in das gewünschte Format analysiert.

CSV-Dateien in C# lesen: Ein Tutorial, Abbildung 8: Zusammenfassungstabelle für jeden Datentyp Zusammenfassungstabelle für jeden Datentyp

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

Dieser Code zeigt die folgende Ausgabe an:

CSV-Dateien in C# lesen: Ein Tutorial, Abbildung 9: Konsolenausgabe mit korrektem Datentyp Konsolenausgabe mit korrektem Datentyp

Und wir können die Werte der Excel-Datei sample.xlsx hier sehen:

CSV-Dateien in C# lesen: Ein Tutorial, Abbildung 10: Korrekte Datentypen in Excel anzeigen Korrekte Datentypen in Excel anzeigen

Um Excel-Dateidaten in den booleschen Datentyp zu parsen, bietet IronXL die BoolValue-Funktion. Es kann wie folgt verwendet werden:

// 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. Wie man Excel-Dateien in C#-Sammlungen analysiert

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 Wie man ein Excel-WorkSheet in eine DataTable umwandelt

Eine ausgezeichnete Funktion von IronXL ist, dass wir leicht ein spezifisches Excel-WorkSheet in eine DataTable umwandeln können. Zu diesem Zweck können wir die .ToDataTable()-Funktion von IronXL wie folgt verwenden:

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 Wie man eine Excel-Datei in ein DataSet umwandelt

Wenn wir eine vollständige Excel-Datei in ein DataSet parsen möchten, dann können wir zu diesem Zweck die .ToDataSet()-Funktion in IronXL verwenden.

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-Daten innerhalb eines bestimmten Bereichs lesen

IronXL bietet eine intelligente Methode zum Lesen von Excel-Dateidaten innerhalb eines bestimmten Bereichs. Der Bereich kann sowohl auf Zeilen als auch auf Spalten angewendet werden.

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

Der obige Code zeigt die folgende Ausgabe an:

CSV-Dateien in C# lesen: Ein Tutorial, Abbildung 11: Konsolenausgabe, um alle Werte im Bereich B3:B8 zuzugreifen Konsolenausgabe, um alle Werte im Bereich B3:B8 zuzugreifen

Und produziert die Excel-Datei sample.xlsx Werte:

CSV-Dateien in C# lesen: Ein Tutorial, Abbildung 12: Datendarstellung aus sample.xlsx Datendarstellung aus 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. Wie man boolesche Daten in einer Excel-Datei liest

In der Anwendungsentwicklung müssen wir Entscheidungen basierend auf dem booleschen Datentyp in Excel-Dateien treffen.

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

Daraus erhalten wir die Ausgabe:

CSV-Dateien in C# lesen: Ein Tutorial, Abbildung 13: Konsolenausgabe beim Abrufen von Booleschen Daten Konsolenausgabe beim Abrufen von Booleschen Daten

Und die Excel-Datei sample.xlsx mit Werten von C1 bis C10:

CSV-Dateien in C# lesen: Ein Tutorial, Abbildung 14: Excel-Beispiel zum Vergleich mit Konsolenausgabe Excel-Beispiel zum Vergleich mit Konsolenausgabe

12. Wie man ein vollständiges Excel-WorkSheet liest

Es ist einfach, ein vollständiges Excel-WorkSheet mit Hilfe von Zeilen- und Spaltenindizes zu lesen. Zu diesem Zweck verwenden wir zwei Schleifen: eine zum Durchlesen aller Zeilen und die zweite zum Durchlesen aller Spalten einer spezifischen Zeile. Dann können wir leicht alle Zellwerte im gesamten Excel-WorkSheet erhalten.

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

CSV-Dateien in C# lesen: Ein Tutorial, Abbildung 15: Konsolenausgabe beim Lesen aller Werte Konsolenausgabe beim Lesen aller Werte

13. Wie man Excel-Dateien ohne Interop liest

IronXL ist eine Excel-Bibliothek für C# und .NET, die es Entwicklern ermöglicht, Excel-Daten aus XLS und XLSX-Dokumenten ohne Verwendung von Microsoft.Office.Interop.Excel zu lesen und zu bearbeiten.

Die API ermöglicht es uns, Excel-Dateien intuitiv zu erstellen, zu lesen, zu bearbeiten, zu speichern und zu exportieren für:

  1. .NET Framework 4.5+
  2. .NET Core 2+
  3. .NET Standard
  4. Xamarin
  5. Windows Mobile
  6. Mono
  7. & Azure Cloud Hosting
  8. Blazor
  9. .NET MAUI

Fügen Sie die folgenden Namespaces hinzu:

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

Schreiben Sie nun den folgenden Code in die Hauptfunktion.

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

CSV-Dateien in C# lesen: Ein Tutorial, Abbildung 16: Konsolenausgabe von jeder Zelle Konsolenausgabe von jeder Zelle

IronXL unterstützt auch vollständig ASP.NET, MVC, Windows, macOS, Linux, iOS und Android Mobile-Anwendungsentwicklung.

14. Fazit und Iron XL Spezialangebot

Zusätzlich zum CSV-Parsing in C#, konvertiert IronXL CSV-Dateien mit nur zwei Codezeilen in Excel!

Mit C# oder VB.NET ist es sehr einfach, IronXLs Excel-API ohne Interoperabilität zu verwenden. Sie können Excel-Tabellen lesen, bearbeiten und erstellen oder mit anderen Excel-Formaten wie XLS/XLSX/CSV/TSV arbeiten. Mit der Unterstützung mehrerer Frameworks können Sie 5 Produkte zum Preis von zwei kaufen. Klicken Sie auf unsere Preisseite für weitere Informationen.

CSV-Dateien in C# lesen: Ein Tutorial, Abbildung 17: 5 Produkte der Iron Suite 5 Produkte der Iron Suite

Häufig gestellte Fragen

Wie kann ich eine CSV-Datei in C# lesen?

Um eine CSV-Datei in C# zu lesen, können Sie IronXL verwenden, indem Sie die Bibliothek über NuGet in Visual Studio installieren. Sobald installiert, verwenden Sie die WorkBook.LoadCSV-Methode, um die CSV-Datei zu laden und zu interpretieren.

Was ist CSV und warum kann es komplex sein, in C# zu handhaben?

CSV ist ein einfaches Datenformat, kann aber aufgrund unterschiedlicher Trennzeichen komplex zu handhaben sein. IronXL vereinfacht das Lesen und Parsen von CSV-Dateien in C#-Projekten.

Kann ich CSV-Dateien mit C# in Excel umwandeln?

Ja, IronXL ermöglicht es Ihnen, CSV-Dateien in Excel-Formate wie XLS oder XLSX zu konvertieren, indem Sie die CSV-Datei laden und mit der WorkBook.SaveAs-Methode speichern.

Wie installiere ich IronXL in einem C#-Projekt?

Sie können IronXL installieren, indem Sie den NuGet-Paket-Manager in Visual Studio verwenden. Suchen Sie nach 'IronXL.Excel' und fügen Sie es Ihrem Projekt hinzu, um mit Excel-Dateien zu arbeiten.

Ist es möglich, Excel-Zelldaten in spezifische Datentypen in C# zu parsen?

Ja, mit IronXL können Sie Excel-Zellwerte in spezifische Datentypen wie numerisch und Boolean parsen, indem Sie Methoden wie Int32Value und BoolValue verwenden.

Wie kann ich Daten aus einem bestimmten Zellbereich in einem Excel-Blatt mit C# lesen?

Mit IronXL können Sie Daten aus bestimmten Zellen lesen, indem Sie den Bereich mit einer Schleife durchlaufen und Zellwerte über die Indizierungsfähigkeiten von IronXL zugreifen.

Wie konvertiere ich ein Excel-Arbeitsblatt in eine DataTable in C#?

Sie können ein Excel-Arbeitsblatt mit der WorkSheet.ToDataTable-Methode von IronXL in eine DataTable konvertieren, die das Arbeitsblatt effizient in ein DataTable-Objekt für die Datenmanipulation parst.

Brauche ich Microsoft Office Interop, um Excel-Dateien programmgesteuert zu lesen?

Nein, mit IronXL können Sie Excel-Dateien lesen und manipulieren, ohne Microsoft Office Interop zu benötigen, was es zu einer eigenständigen und effizienten Lösung macht.

Was sind die Vorteile von IronXL für das Handling von Excel- und CSV-Dateien?

IronXL bietet einfache Installation, keine Abhängigkeit von Interop, Unterstützung für mehrere Excel-Formate und Kompatibilität mit verschiedenen .NET-Frameworks, was die Produktivität beim Umgang mit CSV- und Excel-Dateien erhöht.

Wie lese ich ein vollständiges Excel-Arbeitsblatt in C#?

Um ein vollständiges Excel-Arbeitsblatt mit IronXL zu lesen, können Sie verschachtelte Schleifen verwenden, um alle Zeilen und Spalten zu durchqueren und Zellwerte mit den Methoden von IronXL zu extrahieren.

Jordi Bardia
Software Ingenieur
Jordi ist am besten in Python, C# und C++ versiert. Wenn er nicht bei Iron Software seine Fähigkeiten einsetzt, programmiert er Spiele. Mit Verantwortung für Produkttests, Produktentwicklung und -forschung trägt Jordi mit immensem Wert zur kontinuierlichen Produktverbesserung bei. Die abwechslungsreiche Erfahrung hält ihn gefordert und engagiert, ...
Weiterlesen