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 schwierig sein, programmatisch in unseren C#- Projekten zu lesen, da es mehrere Trennzeichen verwendet, um zwischen Zeilen und Spalten von Daten zu unterscheiden. Dieser Artikel zeigt Ihnen, wie Sie die IronXL-Bibliothek verwenden, um CSV-Dateien zu lesen.
1. How to read a CSV File 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.
- Wählen Sie im Visual Studio das Menü Projekt
- Verwalten Sie NuGet-Pakete
- Suchen Sie nach IronXL.Excel
- Installieren
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")
Ausgabe:
CSV-Datei mit Komma-Trennzeichen ausgeben
Code-Erklärung:
Es wird ein WorkBook Objekt erstellt. Anschließend wird die Methode LoadCSV des WorkBook-Objekts verwendet, um den Namen der CSV-Datei, ihr Format und die in der zu lesenden CSV-Datei verwendeten Trennzeichen anzugeben. In diesem Fall werden Kommas als Trennzeichen verwendet.
Anschließend wird ein WorkSheet- Objekt erstellt. Hier werden die Inhalte der CSV-Datei abgelegt. Die Datei wird unter einem neuen Namen und Format gespeichert.
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. Lade WorkBook und greife auf WorkSheet zu.
WorkBook ist die Klasse von IronXL , deren Objekt vollen Zugriff auf die Excel-Datei und alle ihre Funktionen ermöglicht. 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
Um auf das spezifische Arbeitsblatt einer Excel-Datei zuzugreifen, stellt IronXL die Klasse WorkSheet zur Verfügung.
// 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
Sobald Sie das Excel-Arbeitsblatt ws erhalten haben, können Sie beliebige Daten daraus extrahieren und alle Excel-Funktionen darauf anwenden. Die Daten können über folgenden Prozess aus dem Excel-Arbeitsblatt ws 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
4. Lesen eines Excel-WorkSheet als DataTable
Mit IronXL ist es sehr einfach, mit einer Excel-Tabelle 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
Verwenden Sie die folgenden Namensräume:
using IronXL;
using System.Data;
using IronXL;
using System.Data;
Imports IronXL
Imports System.Data
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
Konsolenausgabe von einem DataTable-Objekt
In diesem Beispiel werden wir uns ansehen, 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
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
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 beim Konvertieren von CSV in C# .NET entdeckt, indem ich ein anpassbares Trennzeichen anstelle von string.Split(',') zur Trennung der Werte durch Kommas angegeben habe.
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
Konsolenausgabe von DataTable
7. Daten aus Excel-Dateien abrufen
Jetzt können wir mithilfe verschiedener Methoden ganz einfach Daten jeder Art aus dem geöffneten Excel abrufen WorkSheet. Im folgenden Beispiel sehen wir, wie man auf einen bestimmten Zellenwert zugreift und ihn in string parst:
// 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()
In der obigen Zeile ist ws der WorkSheet, der in Schritt 2 definiert wurde. Dies ist der einfache Ansatz, aber Sie können mehr darüber lesen und verschiedene Beispiele sehen, wie Sie auf Excel-Dateidaten zugreifen können .
8. How to Parse Excel Files in C
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
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.
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
Dieser Code zeigt die folgende Ausgabe an:
Konsolenausgabe mit korrektem Datentyp
Und wir können die Werte der Excel-Datei sample.xlsx hier sehen:
Korrekte Datentypen in Excel anzeigen
Um Excel-Dateidaten in den Datentyp Boolean zu parsen, stellt IronXL die Funktion BoolValue zur Verfügung. 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
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
10.1 So parsen Sie eine Excel-Datei WorkSheet in eine DataTable
Eine hervorragende Funktion von IronXL ist, dass wir eine bestimmte Excel-Datei (WorkSheet) ganz einfach in eine DataTable konvertieren 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
10.2 Wie man eine Excel-Datei in ein DataSet umwandelt
Wenn wir eine komplette Excel-Datei in ein DataSet parsen möchten, können wir zu diesem Zweck die Funktion .ToDataSet() 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
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
Der obige Code zeigt die folgende Ausgabe an:
Konsolenausgabe, um alle Werte im Bereich B3:B8 zuzugreifen
Und produziert die Excel-Datei sample.xlsx Werte:
Datendarstellung aus sample.xlsx
Zusätzlich ist IronXL auch mit vielen Excel-Methoden kompatibel, um mit Zellen zu interagieren, einschließlich Formatierungen und Rahmen, Mathefunktionen, bedingte Formatierungen oder das Erstellen von Diagrammen aus vorhandenen Daten.
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
Daraus erhalten wir die Ausgabe:
Konsolenausgabe beim Abrufen von Booleschen Daten
Und die Excel-Datei sample.xlsx mit Werten von C1 bis C10:
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
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:
- .NET Framework 4.5+
- .NET Core 2+
- .NET Standard
- Xamarin
- Windows Mobile
- Mono
- & Azure Cloud Hosting
- Blazor
- .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
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
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.
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.




