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);
Pour travailler avec différents formats Excel, il faut souvent lire les données puis les reconfigurer par programme. Dans cet article, nous allons apprendre à lire un fichier C# et à analyser les données d'une feuille de calcul Excel en C# à l'aide d'IronXL, l'outil idéal pour ce travail.
Qu'est-ce que le CSV ?
Le format CSV est un format de données simple, mais il peut être difficile de le lire de manière programmatique dans nos projets C#, car il utilise plusieurs délimiteurs pour distinguer les lignes et les colonnes de données. Cet article va vous montrer comment utiliser la bibliothèque IronXL pour lire des fichiers CSV.
1. Comment lire un fichier CSV en C# ;
Avant de pouvoir faire usage d'IronXL pour lire des fichiers CSV dans MVC, ASP.NET ou .NET Core, vous devez l'installer. Voici un aperçu rapide de la situation.
Dans Visual Studio, sélectionnez le menu Projet
Gérer les paquets NuGet
Recherche d'IronXL.Excel
Installer
Recherchez IronXL dans le gestionnaire de packages NuGet dans Visual Studio
Lorsque vous devez lire des fichiers CSV en C#, IronXL est l'outil idéal. Vous pouvez lire un fichier CSV avec des virgules ou tout autre délimiteur, comme le montrent les segments de code ci-dessous.
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
Sortie :
Fichier CSV de sortie avec séparateur de virgule
Explication du code :
Un objet WorkBook est créé. La méthode LoadCSV pour l'objet WorkBook est ensuite utilisée pour spécifier le nom du CSV, son format, et quels délimiteurs sont utilisés dans le fichier CSV à lire. Dans ce cas, les virgules sont utilisées comme délimiteurs.
Un objet WorkSheet est ensuite créé. C'est là que le contenu du fichier CSV sera placé. Le fichier est ensuite enregistré sous un nouveau nom et un nouveau format.
WorkBook est la classe d'IronXL dont l'objet permet un accès complet au fichier Excel et à toutes ses fonctions. Par exemple, si nous voulons accéder à un fichier Excel, nous utiliserons le code :
Dim wb As WorkBook = WorkBook.Load("sample.xlsx") 'Excel file path
$vbLabelText $csharpLabel
Pour accéder à la feuille de calcul spécifique d'un fichier Excel, IronXL fournit la classe WorkSheet.
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
Une fois que vous avez obtenu la feuille de calcul Excel ws, vous pouvez extraire tout type de données et effectuer toutes les fonctions Excel dessus. Les données peuvent être accessibles à partir de la feuille de calcul Excel ws dans ce processus :
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. Lecture d'une feuille de calcul Excel en tant que tableau de données
Avec IronXL, il est très facile de travailler avec une feuille de calcul Excel WorkSheet comme un DataTable.
DataTable dt = WorkSheet.ToDataTable();
DataTable dt = WorkSheet.ToDataTable();
Dim dt As DataTable = WorkSheet.ToDataTable()
$vbLabelText $csharpLabel
Utilisez l'espace de noms suivant
using IronXL;
using System.Data;
using IronXL;
using System.Data;
Imports IronXL
Imports System.Data
$vbLabelText $csharpLabel
Ecrivez le code suivant :
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
Sortie de la console d'un objet DataTable
Dans cet exemple, nous allons voir comment utiliser un fichier Excel comme un DataSet.
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
Accéder au nom de feuille à partir de l'objet DataSet
Examinons un autre exemple de la manière d'accéder à chaque valeur de cellule dans toutes les feuilles Excel. Ici, nous pouvons accéder à la valeur de chaque cellule de chaque feuille de calcul d'un fichier Excel.
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
Sortie de la console de l'objet Dataset
5. Analyse CSV dans C&num ; .NET
Les CSV présentent une multitude de problèmes liés à la gestion des sauts de ligne dans les champs, ou à la façon dont les champs peuvent être contenus dans des guillemets, ce qui bloque complètement une approche simple de division de chaîne. J'ai récemment découvert les options suivantes lors de la conversion de CSV en C# .NET en spécifiant un délimiteur personnalisable au lieu d'utiliser string.Split(',') pour séparer les valeurs par une virgule.
6. Lecture de données C# dans C&num ; Enregistrements
Ce processus permet au lecteur de passer au fichier suivant. Nous lisons les fichiers de champs CSV dans trygetfield. Nous utilisons la fonction de lecture sur les champs des fichiers CSV en tant que champs d'enregistrement.
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
Sortie de la console depuis DataTable
7. Obtenir des données à partir de fichiers Excel
Désormais, nous pouvons facilement obtenir n'importe quel type de données, à l'aide de diverses méthodes, à partir de la feuille de calcul Excel ouverte. Dans l'exemple suivant, nous pouvons voir comment accéder à une valeur de cellule spécifique et la convertir en string :
//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
Dans la ligne ci-dessus, ws est la feuille de calcul, qui a été définie à l'étape 2. C'est « l'approche simple », mais vous pouvez en lire plus et voir différents exemples de comment accéder aux données des fichiers Excel.
8. Comment analyser les fichiers Excel en C# ;
Lorsque nous utilisons des feuilles de calcul Excel pour la création d'applications, nous analysons souvent les résultats en fonction des données et nous devons analyser les données du fichier Excel dans le format requis au sein de C# afin d'obtenir les bons résultats. L'analyse des données dans différents formats est facilitée dans l'environnement C# par l'utilisation d'IronXL ; voir les étapes ci-dessous.
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. Comment analyser des données Excel en valeurs numériques et booléennes ?
Nous allons maintenant voir comment analyser les données d'un fichier Excel. Tout d'abord, nous verrons comment traiter les données numériques d'Excel, puis comment les analyser dans le format requis.
Tableau récapitulatif pour chaque type de données
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
Ce code affichera la sortie suivante :
Sortie de console avec le bon type de données
Nous pouvons voir ici les valeurs du fichier Excel sample.xlsx :
Afficher le type de données correct dans Excel
Pour analyser les données d'un fichier Excel en type de données booléennes, IronXL fournit la fonction BoolValue. Il peut être utilisé comme suit :
bool Val = ws ["Cell Address"].BoolValue;
bool Val = ws ["Cell Address"].BoolValue;
Dim Val As Boolean = ws ("Cell Address").BoolValue
$vbLabelText $csharpLabel
10. Comment analyser les fichiers Excel en C# ; Collections
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 Comment analyser une WorkSheet Excel en un DataTable
Une caractéristique excellente d'IronXL est que nous pouvons facilement convertir un WorkSheet Excel spécifique en un DataTable. À cette fin, nous pouvons utiliser la fonction .ToDataTable() de IronXL comme suit :
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 Comment analyser un fichier Excel dans un DataSet ?
Si nous voulons analyser un fichier Excel complet en un DataSet, nous pouvons utiliser la fonction .ToDataSet() dans IronXL à cet effet.
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 Lecture de données Excel dans une plage spécifique
IronXL fournit une méthode intelligente pour lire les données d'un fichier Excel à l'intérieur d'une plage spécifique. La plage peut être appliquée à la fois aux lignes et aux colonnes.
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
Le code ci-dessus affiche la sortie suivante :
Sortie de la console pour accéder à toutes les valeurs dans la plage B3:B8
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
Nous obtenons ainsi le résultat :
Sortie de la console pour obtenir des données booléennes
Et le fichier Excel sample.xlsx avec les valeurs de C1 à C10 :
Exemple Excel à comparer avec la sortie de la console
12. Comment lire une feuille de calcul Excel complète
Il est simple de lire une feuille de calcul Excel complète en utilisant les index des lignes et des colonnes. À cette fin, nous utilisons deux boucles : l'une pour parcourir toutes les lignes et l'autre pour parcourir toutes les colonnes d'une ligne spécifique. Nous pouvons alors facilement obtenir toutes les valeurs des cellules dans l'ensemble de la feuille de calcul Excel.
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
Sortie de la console lors de la lecture de toutes les valeurs
13. Comment lire des fichiers Excel sans interopérabilité
IronXL est une bibliothèque Excel pour C# et .NET qui permet aux développeurs de lire et de modifier les données Excel à partir de documents XLS et XLSXsans utiliser Microsoft.Office.Interop.Excel.
L'API nous permet de créer, lire, manipuler, enregistrer et exporter des fichiers Excel de manière intuitive :
Écrivez maintenant le code suivant à l'intérieur de la fonction principale.
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
Sortie de la console de chaque cellule
IronXL prend également entièrement en charge le développement d'applications mobiles ASP.NET, MVC, Windows, macOS, Linux, iOS et Android.
14. Offre spéciale Conclusion et Iron XL
En plus de la parsing CSV en C#, IronXL convertit les fichiers CSV en Excel avec seulement deux lignes de code !
En utilisant C# ou VB.NET, il est très facile d'utiliser l'API Excel de IronXL sans avoir besoin d'Interop. Vous pouvez lire, modifier et créer des feuilles de calcul Excel ou travailler avec d'autres formats Excel tels que XLS/XLSX/CSV/TSV. Avec le soutien de plusieurs cadres, vous pouvez acheter 5 produits pour le prix de deux. Cliquez sur notre page de tarification pour plus d'informations.
Regan est diplômé de l'université de Reading, où il a obtenu une licence en ingénierie électronique. Avant de rejoindre Iron Software, il s'était concentré sur une seule tâche. Ce qu'il apprécie le plus chez Iron Software, c'est la diversité des tâches qu'il peut accomplir, qu'il s'agisse d'apporter une valeur ajoutée aux ventes, à l'assistance technique, au développement de produits ou à la commercialisation. Il aime comprendre comment les développeurs utilisent la bibliothèque d'Iron Software et utiliser ces connaissances pour améliorer continuellement la documentation et développer les produits.
< PRÉCÉDENT Comment mettre en évidence une ligne sur deux dans Excel
SUIVANT > Comment verrouiller des cellules dans Excel : un tutoriel étape par étape
Des millions d'ingénieurs dans le monde entier lui font confiance
Réservez une démo en direct gratuite
Réservez une démonstration personnelle de 30 minutes.
Pas de contrat, pas de détails de carte, pas d'engagements.
Voici ce à quoi vous pouvez vous attendre :
Une démonstration en direct de notre produit et de ses principales fonctionnalités
Obtenez des recommandations de fonctionnalités spécifiques au projet
Toutes vos questions trouvent réponse pour vous assurer de disposer de toutes les informations dont vous avez besoin. (Aucun engagement de votre part.)
CHOISIR L'HEURE
VOS INFORMATIONS
Réservez votre démo en direct gratuite
Fiable par plus de 2 millions d'ingénieurs dans le monde entier