Test dans un environnement réel
Test en production sans filigrane.
Fonctionne partout où vous en avez besoin.
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.
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 vous montrera comment utiliser la fonctionBibliothèque IronXL pour lire les fichiers CSV.
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
Recherche d'IronXL dans le gestionnaire de paquets 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.
WorkBook workbook = WorkBook.LoadCSV("Weather.csv", fileFormat: ExcelFileFormat.XLSX, ListDelimiter: ",");
WorkSheet ws = workbook.DefaultWorkSheet;
workbook.SaveAs("Csv_To_Excel.xlsx");
WorkBook workbook = WorkBook.LoadCSV("Weather.csv", fileFormat: ExcelFileFormat.XLSX, ListDelimiter: ",");
WorkSheet ws = workbook.DefaultWorkSheet;
workbook.SaveAs("Csv_To_Excel.xlsx");
Dim workbook As WorkBook = WorkBook.LoadCSV("Weather.csv", fileFormat:= ExcelFileFormat.XLSX, ListDelimiter:= ",")
Dim ws As WorkSheet = workbook.DefaultWorkSheet
workbook.SaveAs("Csv_To_Excel.xlsx")
Output:
Fichier CSV en sortie avec délimitation par une virgule
Code Explanation:
AWorkBook
(livre de travail) est créé. LesLoadCSV
de l'objet WorkBook est ensuite utilisée pour spécifier le nom du fichier CSV et son format, ainsi que les délimiteurs utilisés dans le fichier CSV en cours de lecture. Dans ce cas, les virgules sont utilisées comme délimiteurs.
AFeuille de travail
est alors 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.
**Données affichées dans Microsoft Excel
Utilisez IronXL pour votre projet comme moyen simplifié de travailler avec les formats de fichiers Excel en C#. Vous pouvez soitinstaller IronXL par téléchargement direct. Vous pouvez également utiliserInstallation de NuGet pour Visual Studio. Le logiciel est gratuit pour le développement.
Install-Package IronXL.Excel
WorkBook
et accéder à WorkSheet
WorkBook
est la classe d'IronXL dont l'objet fournit 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 :
WorkBook wb = WorkBook.Load("sample.xlsx");//Excel file path
WorkBook wb = WorkBook.Load("sample.xlsx");//Excel file path
Dim wb As WorkBook = WorkBook.Load("sample.xlsx") 'Excel file path
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
Une fois que vous avez obtenu la feuille de calcul Excel ws
, vous pouvez en extraire n'importe quel type de données et y exécuter toutes les fonctions Excel. Les données sont 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
Avec IronXL, il est très facile d'utiliser une feuille de travail Excel comme table de données.
DataTable dt = WorkSheet.ToDataTable();
DataTable dt = WorkSheet.ToDataTable();
Dim dt As DataTable = WorkSheet.ToDataTable()
Utilisez l'espace de noms suivant
using IronXL;
using System.Data;
using IronXL;
using System.Data;
Imports IronXL
Imports System.Data
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
Sortie de console à partir d'un objet DataTable
Dans cet exemple, nous allons voir comment utiliser un fichier Excel comme DataSet
.
static void Main(string [] args)
{
WorkBook wb = WorkBook.Load("sample.xlsx");
DataSet ds = wb.ToDataSet(); //Parse WorkBook wb into DataSet
foreach (DataTable dt in ds.Tables)
{
Console.WriteLine(dt.TableName);
}
}
static void Main(string [] args)
{
WorkBook wb = WorkBook.Load("sample.xlsx");
DataSet ds = wb.ToDataSet(); //Parse WorkBook wb into DataSet
foreach (DataTable dt in ds.Tables)
{
Console.WriteLine(dt.TableName);
}
}
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
Accéder au nom de la 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
Sortie console de l'objet Dataset
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.
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
Sortie de console de DataTable
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 à la valeur d'une cellule spécifique et l'analyser 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()
Dans la ligne ci-dessus, ws est la feuille de travail définie à l'étape 2. Il s'agit d'une approche "simple", mais vous pouvez en savoir plus et voir différents exemples de la façon deaccéder aux données d'un fichier Excel.
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
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
Ce code affichera la sortie suivante :
Sortie console avec type de données correctes
Nous pouvons voir ici les valeurs du fichier Excel sample.xlsx :
Afficher le bon type de données dans Excel
Pour analyser les données d'un fichier Excel en données de type booléen, IronXL fournit la fonctionBoolValue
fonction. 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
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
Une excellente caractéristique d'IronXL est que nous pouvons facilement convertir une Feuille de Travail
Excel spécifique en une Table de Données. À cette fin, nous pouvons utiliser la fonction.ToDataTable()
fonction d'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
Si nous voulons analyser un fichier Excel complet dans un DataSet, nous pouvons utiliser la fonction.ToDataSet()
dans IronXL.
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
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
Le code ci-dessus affiche la sortie suivante :
Sortie console pour accéder à toutes les valeurs de l'intervalle B3:B8
Et produit le fichier Excel sample.xlsx valeurs :
Affichage des données de l'échantillon.xlsx
En outre, IronXL est également compatible avec de nombreuses méthodes Excel permettant d'interagir avec les cellules, notammentstyle et bordure, fonctions mathématiques, [conditionnel formatage ou la création de graphiques à partir des données disponibles.
Dans le cadre du développement d'applications, nous devons prendre des décisions basées sur le type de données booléen dans les fichiers Excel.
static void Main(string [] args)
{
WorkBook wb = WorkBook.Load("sample.xlsx");
WorkSheet ws = wb.GetWorkSheet("Sheet1");
foreach (var item in ws ["G1:G10"])
{
Console.WriteLine(" Condition is: {0}", item.BoolValue);
}
Console.ReadKey();
}
static void Main(string [] args)
{
WorkBook wb = WorkBook.Load("sample.xlsx");
WorkSheet ws = wb.GetWorkSheet("Sheet1");
foreach (var item in ws ["G1:G10"])
{
Console.WriteLine(" Condition is: {0}", item.BoolValue);
}
Console.ReadKey();
}
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
Nous obtenons ainsi le résultat :
Sortie de la console lors de l'obtention de 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
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
Sortie de la console après lecture de toutes les valeurs
IronXL est uneBibliothèque Excel pour C# et .NET qui permet aux développeurs de lire et d'éditer des données Excel à partir de documents XLS et XLSX sans utiliser Microsoft.Office.Interop.Excel.
L'API nous permet de créer, lire, manipuler, enregistrer et exporter des fichiers Excel de manière intuitive :
framework .NET 4.5+
.NET Core 2+
standard .NET
Xamarin
Windows Mobile
Mono
& ; Azure Cloud Hosting
Ajouter l'espace de noms suivant :
using IronXL;
using System;
using System.Linq;
using IronXL;
using System;
using System.Linq;
Imports IronXL
Imports System
Imports System.Linq
É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
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.
En plus deAnalyse CSV en C#, IronXL convertit les fichiers CSV en fichiers Excel avec seulement deux lignes de code!
En utilisant C# ou VB.NET, il est très facile d'utiliser l'API Excel d'IronXL sans avoir besoin d'interopérabilité. Vous pouvez lire, modifier et créer des feuilles de calcul Excel ou travailler avec d'autres formats Excel tels queXLS/XLSX/CSV/TSV. Avec le soutien de plusieurs cadres, vous pouvez acheter 5 produits pour le prix de deux. Cliquez surnotre page de tarification pour plus d'informations.
5 produits d'Iron Suite
10 produits API .NET pour vos documents de bureau