Lire un fichier CSV en C#
IronXL offre une solution en une ligne pour lire les fichiers CSV en C# en utilisant la méthode LoadCSV. Il prend en charge des délimiteurs personnalisés et la conversion directe en formats Excel pour un traitement fluide des données dans les applications .NET.
Cet exemple montre comment lire un fichier CSV en utilisant la méthode LoadCSV de IronXL et le sauvegarder en tant que classeur Excel avec un code minimal.
-
1Installez IronXL avec NuGet Package Manager
-
2Copiez et exécutez cet extrait de code.
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") -
3Déployez pour tester sur votre environnement de production.
Commencez à utiliser IronXL dans votre projet dès aujourd'hui avec un essai gratuit
Flux de travail minimal (5 étapes)
- Téléchargez et installez la bibliothèque de lecture CSV en C#
- Créer un projet C# ou VB
- Ajoutez l'exemple de code de cette page à votre projet
- Spécifier le chemin CSV et le nom et le format de sortie
- Exécutez le projet pour visualiser le document
Lecture de fichiers CSV dans les applications .NET
- Installer une bibliothèque C# pour la lecture de fichiers CSV (IronXL)
- Lire des fichiers CSV en C#
- Spécifiez le format de fichier et le délimiteur.
Étape 1
Comment installer la bibliothèque IronXL?
Avant d'utiliser IronXL pour lire des fichiers CSV dans MVC, ASP ou .NET Core, vous devez l'installer. Voici un bref aperçu de la situation.
Pourquoi utiliser NuGet Package Manager?
- Dans Visual Studio, sélectionnez le menu Projet
- Gérer les packages NuGet
- Recherchez
IronXL.Excel - Installer
Quelles sont les méthodes alternatives d'installation ?
Ou téléchargez depuis le site Web de Iron Software : https://ironsoftware.com/csharp/excel/packages/IronXL.zip
Pour les développeurs .NET travaillant avec des conteneurs Docker, IronXL peut être configuré dans votre environnement Docker. La bibliothèque prend également en charge le déploiement sur Azure Functions et AWS Lambda pour le traitement de CSV basé sur le cloud.
Didacticiel de prise en main
Comment lire des fichiers CSV de manière programmatique?
Passons maintenant au projet !
Quel espace de noms dois-je importer?
Ajoutez l'espace de nom IronXL :
// This namespace is required to access the IronXL functionalities
using IronXL;// This namespace is required to access the IronXL functionalities
using IronXL;Imports IronXLImports IronXLComment charger et convertir des fichiers CSV?
Ajoutez du code pour lire un fichier CSV de manière programmatique avec IronXL et C# :
// 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")Quelles options de lecture avancée de CSV sont disponibles ?
IronXL propose des fonctionnalités permettant de traiter des fichiers CSV avec diverses configurations. Vous pouvez spécifier différents délimiteurs (points-virgules, tabulations, pipes) et gérer des fichiers avec différents encodages :
// 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
NextÀ quoi ressemble le fichier CSV avant son traitement?
Comment fonctionne la méthode LoadCSV?
Un objet Workbook est créé. La méthode LoadCSV de l'objet Workbook spécifie le fichier CSV à lire, le format dans lequel le lire, et le délimiteur. Dans ce cas, une virgule est utilisée comme séparateur.
Un objet Worksheet est créé dans lequel les contenus CSV sont placés. Le fichier est ensuite enregistré sous un nouveau nom et un nouveau format. Ce processus est utile lorsque vous devez convertir entre différents formats de feuille de calcul.
Puis-je traiter efficacement de grands fichiers CSV ?
IronXL est optimisé pour les performances et gère efficacement les fichiers CSV volumineux. Pour les développeurs travaillant avec des ensembles de données importants, la bibliothèque offre des améliorations significatives de performance dans les versions récentes. Lorsque vous traitez des fichiers volumineux, tenez compte des meilleures pratiques suivantes :
// 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
NextComment puis-je exporter des données CSV vers d'autres formats ?
Après avoir lu des fichiers CSV, vous devrez peut-être exporter les données dans différents formats. IronXL prend en charge plusieurs options d'exportation, y compris la conversion de XLSX en CSV, JSON, XML et HTML. Voici comment exporter vers différents formats :
// 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", ";")Qu'en est-il du travail avec des données CSV dans les applications Web ?
Pour les développeurs ASP.NET, IronXL offre une intégration simple pour lire les fichiers CSV dans les applications Web. Vous pouvez télécharger et traiter des fichiers CSV dans vos projets MVC ou Web API :
// 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 FunctionComment gérer les fichiers CSV avec des données complexes ?
Lorsque vous travaillez avec des fichiers CSV contenant des formules, des caractères spéciaux ou des types de données mixtes, IronXL offre des capacités de gestion fiables. Vous pouvez travailler avec des formules et formater les données des cellules de manière appropriée :
// 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)"Accès rapide à la bibliothèque
Documentation de référence de l'API IronXL
Apprenez-en davantage et partagez vos connaissances sur la fusion, la dissociation et la manipulation de cellules dans les feuilles de calcul Excel grâce à la documentation de référence pratique de l'API IronXL.
Documentation de référence de l'API IronXLQuestions fréquemment posées
Quelle est la solution en une ligne fournie par IronXL pour lire les fichiers CSV en C# ?
IronXL propose la méthode LoadCSV, qui vous permet de lire un fichier CSV en C# avec une simple commande.
Comment puis-je convertir un fichier CSV en Excel en utilisant IronXL ?
Vous pouvez convertir un fichier CSV en Excel en chargeant le CSV avec la méthode LoadCSV puis en le sauvegardant en tant que fichier Excel avec la méthode SaveAs.
Puis-je utiliser des délimiteurs personnalisés lors de la lecture de fichiers CSV avec IronXL ?
Oui, IronXL supporte les délimiteurs personnalisés, vous permettant de spécifier différents caractères tels que des points-virgules, des tabulations ou des barres verticales dans la méthode LoadCSV.
IronXL est-il capable de gérer efficacement les grands fichiers CSV ?
IronXL est optimisé pour la performance et peut gérer efficacement les grands fichiers CSV, ce qui le rend adapté pour traiter des jeux de données volumineux.
Quels sont les différents formats de fichiers vers lesquels je peux exporter des données CSV en utilisant IronXL ?
En utilisant IronXL, vous pouvez exporter des données CSV vers de multiples formats, y compris Excel (XLSX), JSON, XML et HTML.
Comment puis-je lire des fichiers CSV dans une application web ASP.NET MVC avec IronXL ?
Dans une application web ASP.NET MVC, vous pouvez traiter les fichiers CSV téléchargés en utilisant la méthode LoadCSV dans IronXL, qui peuvent ensuite être convertis en DataTable pour l'affichage.
IronXL propose-t-il des options avancées pour gérer des données CSV complexes ?
Oui, IronXL offre des fonctionnalités avancées telles que le travail avec des formules, la gestion des caractères spéciaux et le paramétrage des formats de données pour les cellules lors du traitement de fichiers CSV complexes.
Puis-je installer IronXL via NuGet dans Visual Studio ?
Oui, vous pouvez installer IronXL en utilisant le NuGet Package Manager dans Visual Studio en recherchant IronXL.Excel et en l'ajoutant à votre projet.
Quel espace de noms dois-je importer pour utiliser les fonctionnalités d'IronXL dans mon projet C# ?
Pour accéder aux fonctionnalités d'IronXL, vous devez importer l'espace de noms IronXL dans votre projet C#.
Quels types de projets peuvent bénéficier de l'utilisation d'IronXL pour le traitement de fichiers CSV ?
IronXL est bénéfique pour les applications .NET, y compris les projets MVC, ASP et .NET Core, où une lecture et une conversion fluides des fichiers CSV sont requises.
Curtis Chau détient un baccalauréat en informatique (Université de Carleton) et se spécialise dans le développement front-end avec expertise en Node.js, TypeScript, JavaScript et React. Passionné par la création d'interfaces utilisateur intuitives et esthétiquement plaisantes, Curtis aime travailler avec des frameworks modernes et créer des manuels bien structurés et visuellement attrayants.


