using IronXL;
using System;
using System.Linq;
// Supported for XLSX, XLS, XLSM, XLTX, CSV and TSV
WorkBook workBook = WorkBook.Load("sample.xlsx");
// Select worksheet at index 0
WorkSheet workSheet = workBook.WorkSheets[0];
// Get any existing worksheet
WorkSheet firstSheet = workBook.DefaultWorkSheet;
// Select a cell and return the converted value
int cellValue = workSheet["A2"].IntValue;
// Read from ranges of cells elegantly.
foreach (var cell in workSheet["A2:A10"])
{
Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text);
}
// Calculate aggregate values such as Min, Max and Sum
decimal sum = workSheet["A2:A10"].Sum();
// Linq compatible
decimal max = workSheet["A2:A10"].Max(c => c.DecimalValue);
Bei der Arbeit mit verschiedenen Excel-Formaten ist es oft erforderlich, Daten einzulesen und sie dann programmatisch umzukonfigurieren. In diesem Artikel lernen wir, wie man eine CSV-Datei liest und Daten aus einer Excel-Tabelle in C# mit IronXL, dem perfekten Tool für diese Aufgabe, analysiert.
Was ist CSV?
CSV ist ein einfaches Datenformat, aber es kann viele Unterschiede geben, aber es kann schwierig sein, es programmatisch in unseren C#-Projekten zu lesen, weil es mehrere Begrenzungszeichen zur Unterscheidung zwischen Zeilen und Spalten von Daten verwendet. Dieser Artikel zeigt Ihnen, wie Sie die IronXL-Bibliothek zum Lesen von CSV-Dateien verwenden können.
1. Wie man eine CSV-Datei in C# liest;
Bevor Sie IronXL zum Lesen von CSV-Dateien in MVC, ASP.NET oder .NET Core verwenden können, müssen Sie es installieren. Hier ist ein kurzer Durchgang.
Wählen Sie in Visual Studio das Menü Projekt
Verwalten von NuGet-Paketen
Suche nach IronXL.Excel
Installieren Sie
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 einem anderen Trennzeichen lesen, wie in den nachstehenden Codesegmenten zu sehen ist.
Dim workbook As WorkBook = WorkBook.LoadCSV("Weather.csv", fileFormat:= ExcelFileFormat.XLSX, ListDelimiter:= ",")
Dim ws As WorkSheet = workbook.DefaultWorkSheet
workbook.SaveAs("Csv_To_Excel.xlsx")
$vbLabelText $csharpLabel
Ausgabe:
CSV-Datei mit Komma als Trennzeichen ausgeben
Code-Erklärung:
Ein WorkBook-Objekt wird erstellt. Die LoadCSV-Methode für das WorkBook-Objekt wird dann verwendet, um den Namen des CSV und dessen Format zu spezifizieren, welche Trennzeichen in der gelesenen CSV-Datei verwendet werden. In diesem Fall werden Kommas als Begrenzungszeichen verwendet.
Ein WorkSheet-Objekt wird dann erstellt. Hier wird der Inhalt der CSV-Datei abgelegt. Anschließend wird die Datei unter einem neuen Namen und Format gespeichert.
3. Laden Sie WorkBook und greifen Sie auf WorkSheet zu
WorkBook ist die Klasse von IronXL, deren Objekt vollen Zugriff auf die Excel-Datei und alle ihre Funktionen bietet. Wenn wir zum Beispiel auf eine Excel-Datei zugreifen wollen, würden wir den Code verwenden:
Dim wb As WorkBook = WorkBook.Load("sample.xlsx") 'Excel file path
$vbLabelText $csharpLabel
Um auf das spezifische Arbeitsblatt einer Excel-Datei zuzugreifen, stellt IronXL die WorkSheet-Klasse zur Verfügung.
WorkSheet ws = wb.GetWorkSheet("Sheet1"); //by sheet name
WorkSheet ws = wb.GetWorkSheet("Sheet1"); //by sheet name
Dim ws As WorkSheet = wb.GetWorkSheet("Sheet1") 'by sheet name
$vbLabelText $csharpLabel
Sobald Sie das Excel-Arbeitsblatt ws erhalten haben, können Sie alle Arten von Daten daraus extrahieren und alle Excel-Funktionen darauf ausführen. Daten können in diesem Prozess aus dem Excel-Arbeitsblatt ws abgerufen werden:
using IronXL;
static void Main(string [] args)
{
WorkBook wb = WorkBook.Load("sample.xlsx");
WorkSheet ws = wb.GetWorkSheet("Sheet1");
foreach (var cell in ws ["A2:A10"])
{
Console.WriteLine("value is: {0}", cell.Text);
}
Console.ReadKey();
}
using IronXL;
static void Main(string [] args)
{
WorkBook wb = WorkBook.Load("sample.xlsx");
WorkSheet ws = wb.GetWorkSheet("Sheet1");
foreach (var cell in ws ["A2:A10"])
{
Console.WriteLine("value is: {0}", cell.Text);
}
Console.ReadKey();
}
Imports IronXL
Shared Sub Main(ByVal args() As String)
Dim wb As WorkBook = WorkBook.Load("sample.xlsx")
Dim ws As WorkSheet = wb.GetWorkSheet("Sheet1")
For Each cell In ws ("A2:A10")
Console.WriteLine("value is: {0}", cell.Text)
Next cell
Console.ReadKey()
End Sub
$vbLabelText $csharpLabel
4. Lesen eines Excel-Arbeitsblatts als Datentabelle
Mit IronXL ist es sehr einfach, mit einem Excel-WorkSheet als DataTable zu arbeiten.
DataTable dt = WorkSheet.ToDataTable();
DataTable dt = WorkSheet.ToDataTable();
Dim dt As DataTable = WorkSheet.ToDataTable()
$vbLabelText $csharpLabel
Verwenden Sie den folgenden Namensraum
using IronXL;
using System.Data;
using IronXL;
using System.Data;
Imports IronXL
Imports System.Data
$vbLabelText $csharpLabel
Schreiben Sie den folgenden Code:
static void Main(string [] args)
{
WorkBook wb = WorkBook.Load("Weather.xlsx"); // Your Excel file Name
WorkSheet ws = wb.GetWorkSheet("Sheet1");
DataTable dt = ws.ToDataTable(true);//parse sheet1 of sample.xlsx file into datatable
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();
}
}
static void Main(string [] args)
{
WorkBook wb = WorkBook.Load("Weather.xlsx"); // Your Excel file Name
WorkSheet ws = wb.GetWorkSheet("Sheet1");
DataTable dt = ws.ToDataTable(true);//parse sheet1 of sample.xlsx file into datatable
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();
}
}
Shared Sub Main(ByVal args() As String)
Dim wb As WorkBook = WorkBook.Load("Weather.xlsx") ' Your Excel file Name
Dim ws As WorkSheet = wb.GetWorkSheet("Sheet1")
Dim dt As DataTable = ws.ToDataTable(True) 'parse sheet1 of sample.xlsx file into datatable
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
$vbLabelText $csharpLabel
Konsolenausgabe von einem DataTable-Objekt
In diesem Beispiel werden wir uns ansehen, wie man eine Excel-Datei als DataSet verwendet.
Shared Sub Main(ByVal args() As String)
Dim wb As WorkBook = WorkBook.Load("sample.xlsx")
Dim ds As DataSet = wb.ToDataSet() 'Parse WorkBook wb into DataSet
For Each dt As DataTable In ds.Tables
Console.WriteLine(dt.TableName)
Next dt
End Sub
$vbLabelText $csharpLabel
Blattname aus DataSet-Objekt abrufen
Schauen wir uns ein weiteres Beispiel an, wie man auf jeden Zellwert in allen Excel-Blättern zugreifen kann. Hier können wir auf jeden Zellwert eines jeden Arbeitsblatts in einer Excel-Datei zugreifen.
static void Main(string [] args)
{
WorkBook wb = WorkBook.Load("Weather.xlsx");
DataSet ds = wb.ToDataSet();//behave complete Excel file as DataSet
foreach (DataTable dt in ds.Tables)//behave 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();
}
}
}
static void Main(string [] args)
{
WorkBook wb = WorkBook.Load("Weather.xlsx");
DataSet ds = wb.ToDataSet();//behave complete Excel file as DataSet
foreach (DataTable dt in ds.Tables)//behave 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();
}
}
}
Shared Sub Main(ByVal args() As String)
Dim wb As WorkBook = WorkBook.Load("Weather.xlsx")
Dim ds As DataSet = wb.ToDataSet() 'behave complete Excel file as DataSet
For Each dt As DataTable In ds.Tables 'behave 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
$vbLabelText $csharpLabel
Konsolenausgabe des Dataset-Objekts
5. CSV-Parsing in C#; .NET
Bei CSV gibt es eine Fülle von Problemen mit der Behandlung von Zeilenumbrüchen in Feldern oder mit Feldern in Anführungszeichen, die einen einfachen Ansatz zur Aufteilung von Zeichenketten völlig blockieren. Ich habe kürzlich die folgenden Optionen entdeckt, als ich CSV in C# .NET konvertierte, indem ich einen anpassbaren Trennzeichen festlegte, anstatt string.Split(',') zu verwenden, um die Werte in einem Komma zu trennen.
6. Lesen von CSV-Daten in C# Datensätzen
Auf diese Weise wird der Leser durch die nächste Datei geführt. Wir lesen die CSV-Felddateien in trygetfield. Wir verwenden die Lesefunktion auf Feldfelder der CSV-Dateien als Datensatzfelder.
WorkBook workbook = WorkBook.LoadCSV("Weather.csv", fileFormat: ExcelFileFormat.XLSX, ListDelimiter: ",");
WorkSheet ws = workbook.DefaultWorkSheet;
DataTable dt = ws.ToDataTable(true);//parse sheet1 of sample.xlsx file into datatable
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();
}
WorkBook workbook = WorkBook.LoadCSV("Weather.csv", fileFormat: ExcelFileFormat.XLSX, ListDelimiter: ",");
WorkSheet ws = workbook.DefaultWorkSheet;
DataTable dt = ws.ToDataTable(true);//parse sheet1 of sample.xlsx file into datatable
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();
}
Dim workbook As WorkBook = WorkBook.LoadCSV("Weather.csv", fileFormat:= ExcelFileFormat.XLSX, ListDelimiter:= ",")
Dim ws As WorkSheet = workbook.DefaultWorkSheet
Dim dt As DataTable = ws.ToDataTable(True) 'parse sheet1 of sample.xlsx file into datatable
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
Konsolenausgabe von DataTable
7. Abrufen von Daten aus Excel-Dateien
Jetzt können wir ganz einfach jede Art von Daten mit einer Vielzahl von Methoden aus dem geöffneten Excel-Arbeitsblatt 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 Arbeitsblatt, das 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. Wie man Excel-Dateien in C# analysiert;
Bei der Verwendung von Excel-Kalkulationstabellen für die Erstellung von Anwendungen analysieren wir oft die Ergebnisse auf der Grundlage von Daten und müssen die Daten der Excel-Datei in C# in das erforderliche Format parsen, um die richtigen Ergebnisse zu erhalten. Das Parsen von Daten in verschiedene Formate wird in der C#-Umgebung durch IronXL erleichtert; siehe die folgenden Schritte.
using IronXL;
static void Main(string [] args)
{
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;
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;
static void Main(string [] args)
{
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;
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
Shared Sub Main(ByVal args() As String)
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
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
$vbLabelText $csharpLabel
9. Analysieren von Excel-Daten in numerische und boolesche Werte
Nun gehen wir dazu über, wie man Daten aus Excel-Dateien auswertet. Zunächst sehen wir uns an, wie man mit numerischen Excel-Daten umgeht und wie man sie dann in das gewünschte Format parst.
Zusammenfassungstabelle für jeden Datentyp
static void Main(string [] args)
{
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;
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();
}
static void Main(string [] args)
{
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;
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();
}
Shared Sub Main(ByVal args() As String)
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
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
$vbLabelText $csharpLabel
Dieser Code zeigt die folgende Ausgabe an:
Konsolenausgabe mit korrektem Datentyp
Und hier sehen wir die Werte der Excel-Datei sample.xlsx:
Korrekte Datentypen in Excel anzeigen
Um Excel-Dateidaten in den Booleschen Datentyp zu analysieren, bietet IronXL die BoolValue-Funktion. Sie kann wie folgt verwendet werden:
bool Val = ws ["Cell Address"].BoolValue;
bool Val = ws ["Cell Address"].BoolValue;
Dim Val As Boolean = ws ("Cell Address").BoolValue
$vbLabelText $csharpLabel
10. Wie man Excel-Dateien in C&num analysiert; Sammlungen
static void Main(string [] args)
{
WorkBook wb = WorkBook.Load("sample.xlsx");
WorkSheet ws = wb.GetWorkSheet("Sheet1");
var array = ws ["B6:F6"].ToArray();
int item = array.Count();
string total_items = array [0].Value.ToString();
Console.WriteLine("First item in the array: {0}", item);
Console.WriteLine("Total items from B6 to F6: {0}",total_items);
Console.ReadKey();
}
static void Main(string [] args)
{
WorkBook wb = WorkBook.Load("sample.xlsx");
WorkSheet ws = wb.GetWorkSheet("Sheet1");
var array = ws ["B6:F6"].ToArray();
int item = array.Count();
string total_items = array [0].Value.ToString();
Console.WriteLine("First item in the array: {0}", item);
Console.WriteLine("Total items from B6 to F6: {0}",total_items);
Console.ReadKey();
}
Shared Sub Main(ByVal args() As String)
Dim wb As WorkBook = WorkBook.Load("sample.xlsx")
Dim ws As WorkSheet = wb.GetWorkSheet("Sheet1")
Dim array = ws ("B6:F6").ToArray()
Dim item As Integer = array.Count()
Dim total_items As String = array (0).Value.ToString()
Console.WriteLine("First item in the array: {0}", item)
Console.WriteLine("Total items from B6 to F6: {0}",total_items)
Console.ReadKey()
End Sub
$vbLabelText $csharpLabel
10.1 Wie man ein Excel-WorkSheet in eine DataTable parst
Ein hervorragendes Merkmal von IronXL ist, dass wir ein bestimmtes Excel-WorkSheet einfach in eine DataTable konvertieren können. Zu diesem Zweck können wir die .ToDataTable() Funktion von IronXL wie folgt verwenden:
static void Main(string [] args)
{
WorkBook wb = WorkBook.Load("sample.xlsx");
WorkSheet ws = wb.GetWorkSheet("Sheet1");
//parse sheet1 of sample.xlsx file into DataTable.
//we set parameter true of ToDataTable() function,so first row of Excel file becomes columnname of DataTable
DataTable dt = ws.ToDataTable(true);
}
static void Main(string [] args)
{
WorkBook wb = WorkBook.Load("sample.xlsx");
WorkSheet ws = wb.GetWorkSheet("Sheet1");
//parse sheet1 of sample.xlsx file into DataTable.
//we set parameter true of ToDataTable() function,so first row of Excel file becomes columnname of DataTable
DataTable dt = ws.ToDataTable(true);
}
Shared Sub Main(ByVal args() As String)
Dim wb As WorkBook = WorkBook.Load("sample.xlsx")
Dim ws As WorkSheet = wb.GetWorkSheet("Sheet1")
'parse sheet1 of sample.xlsx file into DataTable.
'we set parameter true of ToDataTable() function,so first row of Excel file becomes columnname of DataTable
Dim dt As DataTable = ws.ToDataTable(True)
End Sub
$vbLabelText $csharpLabel
10.2 Wie man eine Excel-Datei in ein DataSet parst
Wenn wir eine vollständige Excel-Datei in ein DataSet parsen möchten, können wir zu diesem Zweck die .ToDataSet()-Funktion in IronXL verwenden.
static void Main(string [] args)
{
WorkBook wb = WorkBook.Load("sample.xlsx");
//parse WorkBook wb into DataSet
DataSet ds = wb.ToDataSet();
//we also can get DataTable from ds which is actually WorkSheet as:
DataTable dt=ds.Tables [0];
}
static void Main(string [] args)
{
WorkBook wb = WorkBook.Load("sample.xlsx");
//parse WorkBook wb into DataSet
DataSet ds = wb.ToDataSet();
//we also can get DataTable from ds which is actually WorkSheet as:
DataTable dt=ds.Tables [0];
}
Shared Sub Main(ByVal args() As String)
Dim wb As WorkBook = WorkBook.Load("sample.xlsx")
'parse WorkBook wb into DataSet
Dim ds As DataSet = wb.ToDataSet()
'we also can get DataTable from ds which is actually WorkSheet as:
Dim dt As DataTable=ds.Tables (0)
End Sub
$vbLabelText $csharpLabel
10.3 Lesen von Excel-Daten innerhalb eines bestimmten Bereichs
IronXL bietet eine intelligente Methode zum Lesen von Excel-Dateien innerhalb eines bestimmten Bereichs. Der Bereich kann sowohl auf Zeilen als auch auf Spalten angewendet werden.
static void Main(string [] args)
{
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();
}
static void Main(string [] args)
{
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();
}
Shared Sub Main(ByVal args() As String)
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
$vbLabelText $csharpLabel
Der obige Code zeigt die folgende Ausgabe an:
Konsolenausgabe, um auf alle Werte im Bereich B3:B8 zuzugreifen
Shared Sub Main(ByVal args() As String)
Dim wb As WorkBook = WorkBook.Load("sample.xlsx")
Dim ws As WorkSheet = wb.GetWorkSheet("Sheet1")
For Each item In ws ("G1:G10")
Console.WriteLine(" Condition is: {0}", item.BoolValue)
Next item
Console.ReadKey()
End Sub
$vbLabelText $csharpLabel
Daraus ergibt sich 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-Arbeitsblatt liest
Es ist einfach, ein komplettes Excel-Arbeitsblatt zu lesen, indem man Zeilen- und Spaltenindizes verwendet. Zu diesem Zweck verwenden wir zwei Schleifen: eine, um alle Zeilen zu durchlaufen, und die zweite, um alle Spalten einer bestimmten Zeile zu durchlaufen. Dann können wir ganz einfach alle Zellwerte innerhalb des gesamten Excel-Arbeitsblatts abrufen.
static void Main(string [] args)
{
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();
}
static void Main(string [] args)
{
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();
}
Shared Sub Main(ByVal args() As String)
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
$vbLabelText $csharpLabel
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:
Schreiben Sie nun den folgenden Code in die Hauptfunktion.
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);
}
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);
}
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
$vbLabelText $csharpLabel
Konsolenausgabe aus jeder Zelle
IronXL unterstützt auch ASP.NET, MVC, Windows, macOS, Linux, iOS und Android Mobile Anwendungsentwicklung.
14. Fazit und Iron XL Sonderangebot
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, die Excel-API von IronXL ohne Interop 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.
Regan schloss sein Studium an der University of Reading mit einem BA in Elektrotechnik ab. Bevor er zu Iron Software kam, konzentrierte er sich in seinen früheren Jobs auf einzelne Aufgaben. Was ihm bei Iron Software am meisten Spaß macht, ist das Spektrum der Aufgaben, die er übernehmen kann, sei es im Vertrieb, im technischen Support, in der Produktentwicklung oder im Marketing. Es macht ihm Spaß, die Art und Weise zu verstehen, wie Entwickler die Bibliothek von Iron Software nutzen, und dieses Wissen zu nutzen, um die Dokumentation und die Produkte kontinuierlich zu verbessern.
< PREVIOUS So markieren Sie jede zweite Zeile in Excel
NÄCHSTES > Zellen in Excel sperren: eine Schritt-für-Schritt-Anleitung