Eine CSV-Datei in C# lesen
IronXL bietet eine Ein-Zeilen-Lösung zum Lesen von CSV-Dateien in C# mit der LoadCSV-Methode. Es unterstützt benutzerdefinierte Trennzeichen und die direkte Umwandlung in Excel-Formate für eine reibungslose Datenverarbeitung in .NET-Anwendungen.
Dieses Beispiel zeigt, wie man eine CSV-Datei mit der LoadCSV-Methode von IronXL liest und mit minimalem Code als Excel-Arbeitsmappe speichert.
-
1Installieren Sie IronXL mit NuGet Package Manager
-
2Kopieren Sie diesen Codeausschnitt und führen Sie ihn aus.
WorkBook wb = WorkBook.LoadCSV("data.csv", ExcelFileFormat.XLSX, listDelimiter: ","); wb.SaveAs("output.xlsx");Dim wb As WorkBook = WorkBook.LoadCSV("data.csv", ExcelFileFormat.XLSX, listDelimiter:=",") wb.SaveAs("output.xlsx")Dim wb As WorkBook = WorkBook.LoadCSV("data.csv", ExcelFileFormat.XLSX, listDelimiter:=",") wb.SaveAs("output.xlsx") -
3Bereitstellen zum Testen in Ihrer Live-Umgebung
Beginnen Sie noch heute, IronXL in Ihrem Projekt mit einer kostenlosen Testversion zu verwenden
Minimaler Arbeitsablauf (5 Schritte)
- Laden Sie die C# CSV-Lesebibliothek herunter und installieren Sie sie
- Erstellen Sie ein C#- oder VB-Projekt
- Fügen Sie das Codebeispiel von dieser Seite Ihrem Projekt hinzu
- Geben Sie den CSV-Pfad sowie Name und Format der Ausgabe an
- Starten Sie das Projekt, um das Dokument anzuzeigen
Lesen von CSV-Dateien in .NET-Anwendungen
- Installieren Sie eine C#-Bibliothek zum Lesen von CSV-Dateien (IronXL)
- Lesen von CSV-Dateien in C#
- Dateiformat und Begrenzungszeichen angeben
Schritt 1
Wie installiere ich die IronXL-Bibliothek?
Bevor Sie IronXL zum Lesen von CSV-Dateien in MVC, ASP oder .NET Core verwenden können, müssen Sie es installieren. Hier ist ein kurzer Überblick.
Warum sollte ich NuGet Package Manager verwenden?
- Wählen Sie in Visual Studio das Menü Projekt aus
- Verwalten von NuGet-Paketen
- Sucheintrag nach
IronXL.Excel - Installieren
Was sind alternative Installationsmethoden?
Oder laden Sie es von der Iron Software-Website herunter: https://ironsoftware.com/csharp/excel/packages/IronXL.zip
Für .NET-Entwickler, die mit Docker-Containern arbeiten, kann IronXL in Ihrer Docker-Umgebung konfiguriert werden. Die Bibliothek unterstützt auch die Bereitstellung auf Azure Functions und AWS Lambda für cloudbasierte CSV-Verarbeitung.
Anleitung zum Tutorial
Wie kann ich CSV-Dateien programmatisch lesen?
Jetzt zum Projekt!
Welchen Namespace muss ich importieren?
Fügen Sie das IronXL-Namespace hinzu:
// This namespace is required to access the IronXL functionalities
using IronXL;// This namespace is required to access the IronXL functionalities
using IronXL;Imports IronXLImports IronXLWie lade und konvertiere ich CSV-Dateien?
Fügen Sie Code hinzu, um eine CSV-Datei programmatisch mit IronXL und C# zu lesen:
// Load the CSV file into a WorkBook object, specifying the file path, format, and delimiter
WorkBook workbook = WorkBook.LoadCSV("Read_CSV_Ex.csv", fileFormat: ExcelFileFormat.XLSX, listDelimiter: ",");
// Access the default worksheet within the loaded workbook
WorkSheet ws = workbook.DefaultWorkSheet;
// Save the workbook as an Excel file with a specified name
workbook.SaveAs("Csv_To_Excel.xlsx");// Load the CSV file into a WorkBook object, specifying the file path, format, and delimiter
WorkBook workbook = WorkBook.LoadCSV("Read_CSV_Ex.csv", fileFormat: ExcelFileFormat.XLSX, listDelimiter: ",");
// Access the default worksheet within the loaded workbook
WorkSheet ws = workbook.DefaultWorkSheet;
// Save the workbook as an Excel file with a specified name
workbook.SaveAs("Csv_To_Excel.xlsx");' Load the CSV file into a WorkBook object, specifying the file path, format, and delimiter
Dim workbook As WorkBook = WorkBook.LoadCSV("Read_CSV_Ex.csv", fileFormat:=ExcelFileFormat.XLSX, listDelimiter:=",")
' Access the default worksheet within the loaded workbook
Dim ws As WorkSheet = workbook.DefaultWorkSheet
' Save the workbook as an Excel file with a specified name
workbook.SaveAs("Csv_To_Excel.xlsx")' Load the CSV file into a WorkBook object, specifying the file path, format, and delimiter
Dim workbook As WorkBook = WorkBook.LoadCSV("Read_CSV_Ex.csv", fileFormat:=ExcelFileFormat.XLSX, listDelimiter:=",")
' Access the default worksheet within the loaded workbook
Dim ws As WorkSheet = workbook.DefaultWorkSheet
' Save the workbook as an Excel file with a specified name
workbook.SaveAs("Csv_To_Excel.xlsx")Welche erweiterten CSV-Leseoptionen sind verfügbar?
IronXL bietet Funktionen für die Verarbeitung von CSV-Dateien mit verschiedenen Konfigurationen. Sie können verschiedene Begrenzungszeichen (Semikolon, Tabulator, Pipe) angeben und Dateien mit unterschiedlichen Kodierungen verarbeiten:
// Example: Reading CSV with custom delimiter
WorkBook workbook = WorkBook.LoadCSV("data.csv",
fileFormat: ExcelFileFormat.XLSX,
listDelimiter: ";"); // Using semicolon as delimiter
// Access specific cells after loading
var cellValue = workbook.DefaultWorkSheet["A1"].Value;
// Iterate through rows
foreach (var row in workbook.DefaultWorkSheet.Rows)
{
// Process each row
foreach (var cell in row)
{
Console.WriteLine(cell.Value);
}
}// Example: Reading CSV with custom delimiter
WorkBook workbook = WorkBook.LoadCSV("data.csv",
fileFormat: ExcelFileFormat.XLSX,
listDelimiter: ";"); // Using semicolon as delimiter
// Access specific cells after loading
var cellValue = workbook.DefaultWorkSheet["A1"].Value;
// Iterate through rows
foreach (var row in workbook.DefaultWorkSheet.Rows)
{
// Process each row
foreach (var cell in row)
{
Console.WriteLine(cell.Value);
}
}' Example: Reading CSV with custom delimiter
Dim workbook As WorkBook = WorkBook.LoadCSV("data.csv", fileFormat:=ExcelFileFormat.XLSX, listDelimiter:=";") ' Using semicolon as delimiter
' Access specific cells after loading
Dim cellValue = workbook.DefaultWorkSheet("A1").Value
' Iterate through rows
For Each row In workbook.DefaultWorkSheet.Rows
' Process each row
For Each cell In row
Console.WriteLine(cell.Value)
Next
Next' Example: Reading CSV with custom delimiter
Dim workbook As WorkBook = WorkBook.LoadCSV("data.csv", fileFormat:=ExcelFileFormat.XLSX, listDelimiter:=";") ' Using semicolon as delimiter
' Access specific cells after loading
Dim cellValue = workbook.DefaultWorkSheet("A1").Value
' Iterate through rows
For Each row In workbook.DefaultWorkSheet.Rows
' Process each row
For Each cell In row
Console.WriteLine(cell.Value)
Next
NextWie sieht die CSV-Datei vor der Verarbeitung aus?
Wie funktioniert die LoadCSV-Methode?
Ein Workbook-Objekt wird erstellt. Die LoadCSV-Methode des Workbook-Objekts gibt die zu lesende CSV-Datei, das Format zum Lesen und das Trennzeichen an. In diesem Fall wird ein Komma als Trennzeichen verwendet.
Ein Worksheet-Objekt wird erstellt, in dem die CSV-Inhalte platziert werden. Die Datei wird dann unter einem neuen Namen und in einem neuen Format gespeichert. Dieser Prozess ist nützlich, wenn Sie zwischen verschiedenen Tabellenkalkulationsformaten konvertieren müssen.
Kann ich große CSV-Dateien effizient verarbeiten?
IronXL ist auf Leistung optimiert und kann große CSV-Dateien effizient verarbeiten. Für Entwickler, die mit umfangreichen Datensätzen arbeiten, bietet die Bibliothek erhebliche Leistungsverbesserungen in den neuesten Versionen. Beachten Sie bei der Verarbeitung großer Dateien die folgenden Best Practices:
// Reading large CSV files with memory optimization
WorkBook workbook = WorkBook.LoadCSV("large_dataset.csv",
fileFormat: ExcelFileFormat.XLSX,
listDelimiter: ",");
// Process data in chunks
var worksheet = workbook.DefaultWorkSheet;
int rowCount = worksheet.RowCount;
int batchSize = 1000;
for (int i = 0; i < rowCount; i += batchSize)
{
// Process rows in batches
var endIndex = Math.Min(i + batchSize, rowCount);
for (int j = i; j < endIndex; j++)
{
var row = worksheet.GetRow(j);
// Process individual row
}
}// Reading large CSV files with memory optimization
WorkBook workbook = WorkBook.LoadCSV("large_dataset.csv",
fileFormat: ExcelFileFormat.XLSX,
listDelimiter: ",");
// Process data in chunks
var worksheet = workbook.DefaultWorkSheet;
int rowCount = worksheet.RowCount;
int batchSize = 1000;
for (int i = 0; i < rowCount; i += batchSize)
{
// Process rows in batches
var endIndex = Math.Min(i + batchSize, rowCount);
for (int j = i; j < endIndex; j++)
{
var row = worksheet.GetRow(j);
// Process individual row
}
}Imports System
Imports IronXL
' Reading large CSV files with memory optimization
Dim workbook As WorkBook = WorkBook.LoadCSV("large_dataset.csv",
fileFormat:=ExcelFileFormat.XLSX,
listDelimiter:=",")
' Process data in chunks
Dim worksheet = workbook.DefaultWorkSheet
Dim rowCount As Integer = worksheet.RowCount
Dim batchSize As Integer = 1000
For i As Integer = 0 To rowCount - 1 Step batchSize
' Process rows in batches
Dim endIndex As Integer = Math.Min(i + batchSize, rowCount)
For j As Integer = i To endIndex - 1
Dim row = worksheet.GetRow(j)
' Process individual row
Next
NextImports System
Imports IronXL
' Reading large CSV files with memory optimization
Dim workbook As WorkBook = WorkBook.LoadCSV("large_dataset.csv",
fileFormat:=ExcelFileFormat.XLSX,
listDelimiter:=",")
' Process data in chunks
Dim worksheet = workbook.DefaultWorkSheet
Dim rowCount As Integer = worksheet.RowCount
Dim batchSize As Integer = 1000
For i As Integer = 0 To rowCount - 1 Step batchSize
' Process rows in batches
Dim endIndex As Integer = Math.Min(i + batchSize, rowCount)
For j As Integer = i To endIndex - 1
Dim row = worksheet.GetRow(j)
' Process individual row
Next
NextWie kann ich CSV-Daten in andere Formate exportieren?
Nach dem Lesen von CSV-Dateien müssen Sie die Daten möglicherweise in verschiedene Formate exportieren. IronXL unterstützt mehrere Exportoptionen, einschließlich XLSX-zu-CSV-Konvertierung, JSON, XML und HTML. Hier erfahren Sie, wie Sie in verschiedene Formate exportieren können:
// Load CSV and export to multiple formats
WorkBook workbook = WorkBook.LoadCSV("input.csv", ExcelFileFormat.XLSX, ",");
// Export to different formats
workbook.SaveAs("output.xlsx"); // Excel format
workbook.SaveAsJson("output.json"); // JSON format
workbook.SaveAsXml("output.xml"); // XML format
// Export specific worksheet to CSV with custom delimiter
workbook.DefaultWorkSheet.SaveAsCsv("output_custom.csv", ";");// Load CSV and export to multiple formats
WorkBook workbook = WorkBook.LoadCSV("input.csv", ExcelFileFormat.XLSX, ",");
// Export to different formats
workbook.SaveAs("output.xlsx"); // Excel format
workbook.SaveAsJson("output.json"); // JSON format
workbook.SaveAsXml("output.xml"); // XML format
// Export specific worksheet to CSV with custom delimiter
workbook.DefaultWorkSheet.SaveAsCsv("output_custom.csv", ";");' Load CSV and export to multiple formats
Dim workbook As WorkBook = WorkBook.LoadCSV("input.csv", ExcelFileFormat.XLSX, ",")
' Export to different formats
workbook.SaveAs("output.xlsx") ' Excel format
workbook.SaveAsJson("output.json") ' JSON format
workbook.SaveAsXml("output.xml") ' XML format
' Export specific worksheet to CSV with custom delimiter
workbook.DefaultWorkSheet.SaveAsCsv("output_custom.csv", ";")' Load CSV and export to multiple formats
Dim workbook As WorkBook = WorkBook.LoadCSV("input.csv", ExcelFileFormat.XLSX, ",")
' Export to different formats
workbook.SaveAs("output.xlsx") ' Excel format
workbook.SaveAsJson("output.json") ' JSON format
workbook.SaveAsXml("output.xml") ' XML format
' Export specific worksheet to CSV with custom delimiter
workbook.DefaultWorkSheet.SaveAsCsv("output_custom.csv", ";")Was ist mit der Arbeit mit CSV-Daten in Webanwendungen?
Für ASP.NET-Entwickler bietet IronXL eine unkomplizierte Integration zur Lesung von CSV-Dateien in Webanwendungen. Sie können CSV-Dateien in Ihren MVC- oder Web-API-Projekten hochladen und verarbeiten:
// Example: Processing uploaded CSV file in ASP.NET
public ActionResult UploadCSV(HttpPostedFileBase file)
{
if (file != null && file.ContentLength > 0)
{
// Save uploaded file temporarily
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/"), fileName);
file.SaveAs(path);
// Load and process CSV
WorkBook workbook = WorkBook.LoadCSV(path, ExcelFileFormat.XLSX, ",");
// Convert to DataTable for easy display
var dataTable = workbook.DefaultWorkSheet.ToDataTable();
// Clean up temporary file
System.IO.File.Delete(path);
return View(dataTable);
}
return RedirectToAction("Index");
}// Example: Processing uploaded CSV file in ASP.NET
public ActionResult UploadCSV(HttpPostedFileBase file)
{
if (file != null && file.ContentLength > 0)
{
// Save uploaded file temporarily
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/"), fileName);
file.SaveAs(path);
// Load and process CSV
WorkBook workbook = WorkBook.LoadCSV(path, ExcelFileFormat.XLSX, ",");
// Convert to DataTable for easy display
var dataTable = workbook.DefaultWorkSheet.ToDataTable();
// Clean up temporary file
System.IO.File.Delete(path);
return View(dataTable);
}
return RedirectToAction("Index");
}' Example: Processing uploaded CSV file in ASP.NET
Public Function UploadCSV(file As HttpPostedFileBase) As ActionResult
If file IsNot Nothing AndAlso file.ContentLength > 0 Then
' Save uploaded file temporarily
Dim fileName = Path.GetFileName(file.FileName)
Dim path = Path.Combine(Server.MapPath("~/App_Data/"), fileName)
file.SaveAs(path)
' Load and process CSV
Dim workbook As WorkBook = WorkBook.LoadCSV(path, ExcelFileFormat.XLSX, ",")
' Convert to DataTable for easy display
Dim dataTable = workbook.DefaultWorkSheet.ToDataTable()
' Clean up temporary file
System.IO.File.Delete(path)
Return View(dataTable)
End If
Return RedirectToAction("Index")
End Function' Example: Processing uploaded CSV file in ASP.NET
Public Function UploadCSV(file As HttpPostedFileBase) As ActionResult
If file IsNot Nothing AndAlso file.ContentLength > 0 Then
' Save uploaded file temporarily
Dim fileName = Path.GetFileName(file.FileName)
Dim path = Path.Combine(Server.MapPath("~/App_Data/"), fileName)
file.SaveAs(path)
' Load and process CSV
Dim workbook As WorkBook = WorkBook.LoadCSV(path, ExcelFileFormat.XLSX, ",")
' Convert to DataTable for easy display
Dim dataTable = workbook.DefaultWorkSheet.ToDataTable()
' Clean up temporary file
System.IO.File.Delete(path)
Return View(dataTable)
End If
Return RedirectToAction("Index")
End FunctionWie gehe ich mit CSV-Dateien mit komplexen Daten um?
Beim Arbeiten mit CSV-Dateien, die Formeln, Sonderzeichen oder gemischte Datentypen enthalten, bietet IronXL zuverlässige Handhabungsmöglichkeiten. Sie können mit Formeln arbeiten und Zelldaten entsprechend formatieren:
// Handle CSV with special requirements
WorkBook workbook = WorkBook.LoadCSV("complex_data.csv",
ExcelFileFormat.XLSX,
listDelimiter: ",");
var worksheet = workbook.DefaultWorkSheet;
// Apply formatting to cells
worksheet["A1:A10"].Style.Font.Bold = true;
worksheet["B1:B10"].FormatString = "$#,##0.00"; // Currency format
// Add formulas after loading CSV data
worksheet["D1"].Formula = "=SUM(B1:B10)";// Handle CSV with special requirements
WorkBook workbook = WorkBook.LoadCSV("complex_data.csv",
ExcelFileFormat.XLSX,
listDelimiter: ",");
var worksheet = workbook.DefaultWorkSheet;
// Apply formatting to cells
worksheet["A1:A10"].Style.Font.Bold = true;
worksheet["B1:B10"].FormatString = "$#,##0.00"; // Currency format
// Add formulas after loading CSV data
worksheet["D1"].Formula = "=SUM(B1:B10)";Imports IronXL
' Handle CSV with special requirements
Dim workbook As WorkBook = WorkBook.LoadCSV("complex_data.csv", ExcelFileFormat.XLSX, listDelimiter:=",")
Dim worksheet = workbook.DefaultWorkSheet
' Apply formatting to cells
worksheet("A1:A10").Style.Font.Bold = True
worksheet("B1:B10").FormatString = "$#,##0.00" ' Currency format
' Add formulas after loading CSV data
worksheet("D1").Formula = "=SUM(B1:B10)"Imports IronXL
' Handle CSV with special requirements
Dim workbook As WorkBook = WorkBook.LoadCSV("complex_data.csv", ExcelFileFormat.XLSX, listDelimiter:=",")
Dim worksheet = workbook.DefaultWorkSheet
' Apply formatting to cells
worksheet("A1:A10").Style.Font.Bold = True
worksheet("B1:B10").FormatString = "$#,##0.00" ' Currency format
' Add formulas after loading CSV data
worksheet("D1").Formula = "=SUM(B1:B10)"Bibliothek Schnellzugriff
IronXL API-Referenzdokumentation
Erfahren Sie mehr und teilen Sie mit anderen, wie Sie Zellen in Excel-Tabellen zusammenführen, aufheben und mit ihnen arbeiten können, indem Sie die praktische IronXl.API-Referenzdokumentation verwenden.
IronXL API-ReferenzdokumentationHäufig gestellte Fragen
Was ist die Ein-Zeilen-Lösung, die IronXL für das Lesen von CSV-Dateien in C# bereitstellt?
IronXL bietet die LoadCSV-Methode, mit der Sie eine CSV-Datei in C# mit einem einfachen Befehl lesen können.
Wie kann ich eine CSV-Datei mit IronXL in Excel konvertieren?
Sie können eine CSV-Datei in Excel konvertieren, indem Sie die CSV-Datei mit der LoadCSV-Methode laden und dann mit der SaveAs-Methode als Excel-Datei speichern.
Kann ich benutzerdefinierte Trennzeichen verwenden, wenn ich CSV-Dateien mit IronXL lese?
Ja, IronXL unterstützt benutzerdefinierte Trennzeichen und ermöglicht Ihnen, verschiedene Zeichen wie Semikolons, Tabs oder Pipes in der LoadCSV-Methode anzugeben.
Ist IronXL in der Lage, große CSV-Dateien effizient zu verarbeiten?
IronXL ist für Leistung optimiert und kann große CSV-Dateien effizient verarbeiten, wodurch es sich für die Bearbeitung umfangreicher Datensätze eignet.
Welche verschiedenen Dateiformate kann ich mit IronXL aus CSV-Daten exportieren?
Mit IronXL können Sie CSV-Daten in mehrere Formate exportieren, einschließlich Excel (XLSX), JSON, XML und HTML.
Wie lese ich CSV-Dateien in einer ASP.NET MVC-Webanwendung mit IronXL?
In einer ASP.NET MVC-Webanwendung können Sie hochgeladene CSV-Dateien mit der LoadCSV-Methode in IronXL verarbeiten, die dann in ein DataTable zur Anzeige umgewandelt werden können.
Bietet IronXL erweiterte Optionen zur Verarbeitung komplexer CSV-Daten?
Ja, IronXL bietet erweiterte Funktionen, wie das Arbeiten mit Formeln, die Verarbeitung von Sonderzeichen und das Festlegen von Zellen-Datenformaten beim Verarbeiten komplexer CSV-Dateien.
Kann ich IronXL über NuGet in Visual Studio installieren?
Ja, Sie können IronXL über den NuGet-Paketmanager in Visual Studio installieren, indem Sie nach IronXL.Excel suchen und es zu Ihrem Projekt hinzufügen.
Welchen Namespace muss ich importieren, um IronXL-Funktionalitäten in meinem C#-Projekt zu verwenden?
Um auf IronXL-Funktionalitäten zuzugreifen, müssen Sie den IronXL-Namespace in Ihr C#-Projekt importieren.
Welche Projektarten können von der Verwendung von IronXL zur Verarbeitung von CSV-Dateien profitieren?
IronXL ist nützlich für .NET-Anwendungen, einschließlich MVC, ASP und .NET Core-Projekte, bei denen reibungsloses CSV-Lesen und Umwandeln erforderlich ist.
Curtis Chau hat einen Bachelor-Abschluss in Informatik von der Carleton University und ist spezialisiert auf Frontend-Entwicklung mit Expertise in Node.js, TypeScript, JavaScript und React. Leidenschaftlich widmet er sich der Erstellung intuitiver und ästhetisch ansprechender Benutzerschnittstellen und arbeitet gerne mit modernen Frameworks sowie der Erstellung gut strukturierter, optisch ansprechender Handbücher.


