C# CSV Dosyaları Okuma: Bir Eğitim
Çeşitli Excel formatlarıyla çalışmak, genellikle verileri okumayı ve ardından programlı olarak yeniden yapılandırmayı gerektirir. Bu makalede, C#'da bir CSV dosyasını nasıl okuyacağımızı ve IronXL kullanarak bir Excel elektronik tablosundan veri nasıl ayrıştıracağımızı öğreneceğiz, bu iş için mükemmel araç.
CSV nedir?
CSV basit bir veri formatıdır, ancak birçok farklılık olabilir; C# projelerimizde programlı olarak okumak zor olabilir çünkü veri satırları ve sütunları arasında ayrım yapmak için birkaç ayrım kullanır. Bu makale, IronXL kütüphanesi ile CSV dosyalarını nasıl okuyacağınızı gösterecek.
1. How to read a CSV File in C
MVC, ASP.NET veya .NET Core'da CSV dosyalarını okumak için IronXL'ı kullanmadan önce, onu yüklemeniz gerekir. İşte hızlı bir gezinme.
- Visual Studio'da Proje menüsünü seçin
- NuGet Paketlerini Yönet
- IronXl.Excel'i arayın
- Yükle
Visual Studio'da NuGet Paket Yöneticisinde IronXL'ı Arayın
C#'da CSV dosyalarını okumak gerektiğinde, IronXL mükemmel bir araçtır. Aşağıdaki kod bölümlerinde de görüldüğü üzere, virgüllü veya başka bir ayraçla bir CSV dosyasını okuyabilirsiniz.
// Load a CSV file and interpret it as an Excel-like workbook
WorkBook workbook = WorkBook.LoadCSV("Weather.csv", fileFormat: ExcelFileFormat.XLSX, ListDelimiter: ",");
// Access the default worksheet in the workbook
WorkSheet ws = workbook.DefaultWorkSheet;
// Save the workbook to a new Excel file
workbook.SaveAs("Csv_To_Excel.xlsx");
// Load a CSV file and interpret it as an Excel-like workbook
WorkBook workbook = WorkBook.LoadCSV("Weather.csv", fileFormat: ExcelFileFormat.XLSX, ListDelimiter: ",");
// Access the default worksheet in the workbook
WorkSheet ws = workbook.DefaultWorkSheet;
// Save the workbook to a new Excel file
workbook.SaveAs("Csv_To_Excel.xlsx");
' Load a CSV file and interpret it as an Excel-like workbook
Dim workbook As WorkBook = WorkBook.LoadCSV("Weather.csv", fileFormat:= ExcelFileFormat.XLSX, ListDelimiter:= ",")
' Access the default worksheet in the workbook
Dim ws As WorkSheet = workbook.DefaultWorkSheet
' Save the workbook to a new Excel file
workbook.SaveAs("Csv_To_Excel.xlsx")
Çıktı:
Virgül Ayraçlı Çıkış CSV Dosyası
Kod Açıklaması:
Bir WorkBook nesnesi oluşturulur. Daha sonra CSV'nin adını, formatını ve okunan CSV dosyasında hangi ayraçların kullanıldığını belirtmek için WorkBook nesnesinin LoadCSV yöntemi kullanılır. Bu durumda, ayırıcı olarak virgüller kullanılır.
Daha sonra bir WorkSheet nesnesi oluşturulur. CSV dosyasının içeriğinin yerleştirileceği yer burasıdır. Dosya yeni bir isim ve format altında kaydedilir.
Microsoft Excel'de veri gösterimi
2. Excel Dosyaları için IronXL
IronXL'i projenizde C#'ta Excel dosya formatlarıyla çalışmanın düz bir yolu olarak kullanın. IronXL'i doğrudan indirme yoluyla yükleyebilirsiniz. Alternatif olarak, Visual Studio için NuGet Yüklemesini kullanabilirsiniz. Yazılım geliştirme için ücretsizdir.
dotnet add package IronXl.Excel
3. WorkBook Yükleme ve WorkSheet Erişme
WorkBook, nesnesi Excel dosyasına ve tüm fonksiyonlarına tam erişim sağlayan IronXL sınıfıdır. Örneğin, bir Excel dosyasına erişmek istiyorsak, şu kodu kullanırız:
// Load the Excel file
WorkBook wb = WorkBook.Load("sample.xlsx"); // Excel file path
// Load the Excel file
WorkBook wb = WorkBook.Load("sample.xlsx"); // Excel file path
' Load the Excel file
Dim wb As WorkBook = WorkBook.Load("sample.xlsx") ' Excel file path
Belirli bir Excel dosyasının çalışma sayfasına erişmek için IronXL, WorkSheet sınıfını sağlar.
// Access a specific worksheet by name
WorkSheet ws = wb.GetWorkSheet("Sheet1"); // by sheet name
// Access a specific worksheet by name
WorkSheet ws = wb.GetWorkSheet("Sheet1"); // by sheet name
' Access a specific worksheet by name
Dim ws As WorkSheet = wb.GetWorkSheet("Sheet1") ' by sheet name
Excel çalışma sayfası ws elde ettiğinizde, her tür veriyi ondan çıkarabilir ve üzerinde tüm Excel işlevlerini gerçekleştirebilirsiniz. Excel çalışma sayfası ws üzerinden veriler şu süreçle erişilebilir:
using IronXL;
class Program
{
static void Main(string[] args)
{
// Load the workbook and access a specific worksheet
WorkBook wb = WorkBook.Load("sample.xlsx");
WorkSheet ws = wb.GetWorkSheet("Sheet1");
// Iterate through a range of cells and display their values
foreach (var cell in ws["A2:A10"])
{
Console.WriteLine("Value is: {0}", cell.Text);
}
Console.ReadKey();
}
}
using IronXL;
class Program
{
static void Main(string[] args)
{
// Load the workbook and access a specific worksheet
WorkBook wb = WorkBook.Load("sample.xlsx");
WorkSheet ws = wb.GetWorkSheet("Sheet1");
// Iterate through a range of cells and display their values
foreach (var cell in ws["A2:A10"])
{
Console.WriteLine("Value is: {0}", cell.Text);
}
Console.ReadKey();
}
}
Imports IronXL
Friend Class Program
Shared Sub Main(ByVal args() As String)
' Load the workbook and access a specific worksheet
Dim wb As WorkBook = WorkBook.Load("sample.xlsx")
Dim ws As WorkSheet = wb.GetWorkSheet("Sheet1")
' Iterate through a range of cells and display their values
For Each cell In ws("A2:A10")
Console.WriteLine("Value is: {0}", cell.Text)
Next cell
Console.ReadKey()
End Sub
End Class
4. Bir Excel Çalışma Sayfasını DataTable Olarak Okumak
IronXL kullanarak bir Excel WorkSheet'i bir DataTable olarak işletmek çok kolaydır.
DataTable dt = ws.ToDataTable(true); // Converts the worksheet to a DataTable, using the first row as column names
DataTable dt = ws.ToDataTable(true); // Converts the worksheet to a DataTable, using the first row as column names
Dim dt As DataTable = ws.ToDataTable(True) ' Converts the worksheet to a DataTable, using the first row as column names
Aşağıdaki ad alanlarını kullanın:
using IronXL;
using System.Data;
using IronXL;
using System.Data;
Imports IronXL
Imports System.Data
Aşağıdaki kodu yazın:
class Program
{
static void Main(string[] args)
{
// Load the workbook and access a specific worksheet
WorkBook wb = WorkBook.Load("Weather.xlsx"); // Your Excel file Name
WorkSheet ws = wb.GetWorkSheet("Sheet1");
// Parse worksheet into datatable
DataTable dt = ws.ToDataTable(true); // Parse Sheet1 of sample.xlsx file into DataTable
// Iterate through rows and columns to display their values
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();
}
}
}
class Program
{
static void Main(string[] args)
{
// Load the workbook and access a specific worksheet
WorkBook wb = WorkBook.Load("Weather.xlsx"); // Your Excel file Name
WorkSheet ws = wb.GetWorkSheet("Sheet1");
// Parse worksheet into datatable
DataTable dt = ws.ToDataTable(true); // Parse Sheet1 of sample.xlsx file into DataTable
// Iterate through rows and columns to display their values
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();
}
}
}
Friend Class Program
Shared Sub Main(ByVal args() As String)
' Load the workbook and access a specific worksheet
Dim wb As WorkBook = WorkBook.Load("Weather.xlsx") ' Your Excel file Name
Dim ws As WorkSheet = wb.GetWorkSheet("Sheet1")
' Parse worksheet into datatable
Dim dt As DataTable = ws.ToDataTable(True) ' Parse Sheet1 of sample.xlsx file into DataTable
' Iterate through rows and columns to display their values
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
End Class
Bir DataTable nesnesinden Konsol çıktısı
Bu örnekte, bir Excel dosyasını DataSet olarak nasıl kullanacağımızı göreceğiz.
class Program
{
static void Main(string[] args)
{
// Load the workbook and convert it to a DataSet
WorkBook wb = WorkBook.Load("sample.xlsx");
DataSet ds = wb.ToDataSet(); // Parse WorkBook wb into DataSet
// Iterate through tables to display their names
foreach (DataTable dt in ds.Tables)
{
Console.WriteLine(dt.TableName);
}
}
}
class Program
{
static void Main(string[] args)
{
// Load the workbook and convert it to a DataSet
WorkBook wb = WorkBook.Load("sample.xlsx");
DataSet ds = wb.ToDataSet(); // Parse WorkBook wb into DataSet
// Iterate through tables to display their names
foreach (DataTable dt in ds.Tables)
{
Console.WriteLine(dt.TableName);
}
}
}
Friend Class Program
Shared Sub Main(ByVal args() As String)
' Load the workbook and convert it to a DataSet
Dim wb As WorkBook = WorkBook.Load("sample.xlsx")
Dim ds As DataSet = wb.ToDataSet() ' Parse WorkBook wb into DataSet
' Iterate through tables to display their names
For Each dt As DataTable In ds.Tables
Console.WriteLine(dt.TableName)
Next dt
End Sub
End Class
DataSet nesnesinden çalışma sayfası adına erişim
Tüm Excel sayfalarındaki her hücre değerine nasıl erişileceğine dair bir başka örneğe bakalım. Burada, bir Excel dosyasındaki her Çalışma Sayfasının her hücre değerine erişebiliriz.
class Program
{
static void Main(string[] args)
{
// Load the workbook and convert it to a DataSet
WorkBook wb = WorkBook.Load("Weather.xlsx");
DataSet ds = wb.ToDataSet(); // Treat the complete Excel file as DataSet
// Iterate through each table and its rows and columns
foreach (DataTable dt in ds.Tables) // Treat 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();
}
}
}
}
class Program
{
static void Main(string[] args)
{
// Load the workbook and convert it to a DataSet
WorkBook wb = WorkBook.Load("Weather.xlsx");
DataSet ds = wb.ToDataSet(); // Treat the complete Excel file as DataSet
// Iterate through each table and its rows and columns
foreach (DataTable dt in ds.Tables) // Treat 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();
}
}
}
}
Friend Class Program
Shared Sub Main(ByVal args() As String)
' Load the workbook and convert it to a DataSet
Dim wb As WorkBook = WorkBook.Load("Weather.xlsx")
Dim ds As DataSet = wb.ToDataSet() ' Treat the complete Excel file as DataSet
' Iterate through each table and its rows and columns
For Each dt As DataTable In ds.Tables ' Treat 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
End Class
Dataset nesnesinin Konsol çıktısı
5. C# .NET'de CSV ayrıştırma
CSV dosyalarında satır sonlarının alanlar içinde nasıl işleme alındığı veya alanların bir basit dizgi bölme yöntemini tamamen engelleyen tırnak içinde nasıl kapsandığıyla ilgili pek çok sorun vardır. '@' ve özelleştirilebilir bir ayraç belirtmek yerine 'string.Split(',')' kullanarak C# .NET'te CSV dönüştürmesi yaparken aşağıdaki seçenekleri keşfettim.
6. C# Kayıtlarında CSV Verilerini Okumak
Bu süreç okuyucuyu bir sonraki dosyaya geçirir. CSV alan dosyalarını TryGetField'da okuyoruz. CSV dosyalarının alan alanları üzerinde okuma işlevini kayıtlardaki alanlar olarak kullanıyoruz.
// Load a CSV file, specify the file format and delimiter
WorkBook workbook = WorkBook.LoadCSV("Weather.csv", fileFormat: ExcelFileFormat.XLSX, ListDelimiter: ",");
// Access the default worksheet from the workbook
WorkSheet ws = workbook.DefaultWorkSheet;
// Convert worksheet to DataTable
DataTable dt = ws.ToDataTable(true); // Parse Sheet1 of sample.xlsx file into DataTable
// Iterate through rows and columns to display their values
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();
}
// Load a CSV file, specify the file format and delimiter
WorkBook workbook = WorkBook.LoadCSV("Weather.csv", fileFormat: ExcelFileFormat.XLSX, ListDelimiter: ",");
// Access the default worksheet from the workbook
WorkSheet ws = workbook.DefaultWorkSheet;
// Convert worksheet to DataTable
DataTable dt = ws.ToDataTable(true); // Parse Sheet1 of sample.xlsx file into DataTable
// Iterate through rows and columns to display their values
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();
}
' Load a CSV file, specify the file format and delimiter
Dim workbook As WorkBook = WorkBook.LoadCSV("Weather.csv", fileFormat:= ExcelFileFormat.XLSX, ListDelimiter:= ",")
' Access the default worksheet from the workbook
Dim ws As WorkSheet = workbook.DefaultWorkSheet
' Convert worksheet to DataTable
Dim dt As DataTable = ws.ToDataTable(True) ' Parse Sheet1 of sample.xlsx file into DataTable
' Iterate through rows and columns to display their values
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
DataTable'dan Konsol çıktısı
7. Excel Dosyalarından Veri Alma
Şimdi, açık olan Excel WorkSheet'den çeşitli yöntemler kullanarak her tür veriyi kolaylıkla alabiliriz. Aşağıdaki örnekte, belirli bir hücre değerine nasıl erişileceğini ve bunu string'ye nasıl çözümleneceğini görebiliriz:
// 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()
Yukarıdaki satırda, ws, 2. Adımda tanımlanan WorkSheet'dir. Bu 'basit' yaklaşımdır, ancak Excel dosya verilerine nasıl erişileceğine dair daha fazla bilgi okuyabilir ve farklı örnekler görebilirsiniz.
8. How to Parse Excel Files in C
Uygulama yapıları için Excel Elektronik Tablolarını kullanırken, sıklıkla sonuçlarını veriye dayalı olarak analiz ederiz ve Excel dosya verilerini C# içinde istediğimiz formata ayrıştırarak doğru sonuçlar elde etmemiz gerekir. Verileri farklı formatlara ayrıştırmak C# Ortamında IronXL kullanımı ile kolaylaşır; aşağıdaki adımlara bakın.
using IronXL;
class Program
{
static void Main(string[] args)
{
// Load the workbook and access a specific worksheet
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;
// Output parsed values to the console
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;
class Program
{
static void Main(string[] args)
{
// Load the workbook and access a specific worksheet
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;
// Output parsed values to the console
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
Friend Class Program
Shared Sub Main(ByVal args() As String)
' Load the workbook and access a specific worksheet
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
' Output parsed values to the console
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
End Class
9. Excel Verilerini Sayısal ve Boolean Değerlere Ayrıştırma
Şimdi Excel dosya verilerini nasıl ayrıştıracağımıza geçiyoruz. Önce sayısal Excel verileri ile nasıl başa çıkılacağını ve ardından istenilen forma nasıl ayrıştırılacağını inceliyoruz.
Her veri türü için özet tablo
class Program
{
static void Main(string[] args)
{
// Load the workbook and access a specific worksheet
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;
// Output parsed values to the console
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();
}
}
class Program
{
static void Main(string[] args)
{
// Load the workbook and access a specific worksheet
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;
// Output parsed values to the console
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();
}
}
Friend Class Program
Shared Sub Main(ByVal args() As String)
' Load the workbook and access a specific worksheet
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
' Output parsed values to the console
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
End Class
Bu kod aşağıdaki çıktıyı gösterecektir:
Doğru veri türü ile Konsol çıktısı
Ve burada sample.xlsx adlı Excel dosyasının değerlerini görebiliriz:
Excel'de doğru veri türü gösterimi
Excel dosyası verilerini Boolean veri türüne çözümlemek için, IronXL BoolValue fonksiyonunu sağlar. Aşağıdaki gibi kullanılabilir:
// Access a cell value as a boolean
bool Val = ws["Cell Address"].BoolValue;
// Access a cell value as a boolean
bool Val = ws["Cell Address"].BoolValue;
' Access a cell value as a boolean
Dim Val As Boolean = ws("Cell Address").BoolValue
10. Excel Dosyalarını C# Koleksiyonlarına Ayrıştırma
class Program
{
static void Main(string[] args)
{
// Load the workbook and access a specific worksheet
WorkBook wb = WorkBook.Load("sample.xlsx");
WorkSheet ws = wb.GetWorkSheet("Sheet1");
// Convert a range into an array
var array = ws["B6:F6"].ToArray();
// Get the count of items in the array
int item = array.Count();
// Get the first item as a string
string total_items = array[0].Value.ToString();
// Output information about the array to the console
Console.WriteLine("First item in the array: {0}", item);
Console.WriteLine("Total items from B6 to F6: {0}", total_items);
Console.ReadKey();
}
}
class Program
{
static void Main(string[] args)
{
// Load the workbook and access a specific worksheet
WorkBook wb = WorkBook.Load("sample.xlsx");
WorkSheet ws = wb.GetWorkSheet("Sheet1");
// Convert a range into an array
var array = ws["B6:F6"].ToArray();
// Get the count of items in the array
int item = array.Count();
// Get the first item as a string
string total_items = array[0].Value.ToString();
// Output information about the array to the console
Console.WriteLine("First item in the array: {0}", item);
Console.WriteLine("Total items from B6 to F6: {0}", total_items);
Console.ReadKey();
}
}
Friend Class Program
Shared Sub Main(ByVal args() As String)
' Load the workbook and access a specific worksheet
Dim wb As WorkBook = WorkBook.Load("sample.xlsx")
Dim ws As WorkSheet = wb.GetWorkSheet("Sheet1")
' Convert a range into an array
Dim array = ws("B6:F6").ToArray()
' Get the count of items in the array
Dim item As Integer = array.Count()
' Get the first item as a string
Dim total_items As String = array(0).Value.ToString()
' Output information about the array to the console
Console.WriteLine("First item in the array: {0}", item)
Console.WriteLine("Total items from B6 to F6: {0}", total_items)
Console.ReadKey()
End Sub
End Class
10.1 Excel WorkSheet'i bir DataTable'a Nasıl Çözümlenir
IronXL'nin harika bir özelliği, belirli bir Excel WorkSheet'i kolayca bir DataTable'a dönüştürebilmemizdir. Bu amaç doğrultusunda, IronXL'in .ToDataTable() fonksiyonunu şu şekilde kullanabiliriz:
class Program
{
static void Main(string[] args)
{
// Load the workbook and access a specific worksheet
WorkBook wb = WorkBook.Load("sample.xlsx");
WorkSheet ws = wb.GetWorkSheet("Sheet1");
// Parse Sheet1 of sample.xlsx file into DataTable
// Setting 'true' makes the first row in Excel as the column names in DataTable
DataTable dt = ws.ToDataTable(true);
}
}
class Program
{
static void Main(string[] args)
{
// Load the workbook and access a specific worksheet
WorkBook wb = WorkBook.Load("sample.xlsx");
WorkSheet ws = wb.GetWorkSheet("Sheet1");
// Parse Sheet1 of sample.xlsx file into DataTable
// Setting 'true' makes the first row in Excel as the column names in DataTable
DataTable dt = ws.ToDataTable(true);
}
}
Friend Class Program
Shared Sub Main(ByVal args() As String)
' Load the workbook and access a specific worksheet
Dim wb As WorkBook = WorkBook.Load("sample.xlsx")
Dim ws As WorkSheet = wb.GetWorkSheet("Sheet1")
' Parse Sheet1 of sample.xlsx file into DataTable
' Setting 'true' makes the first row in Excel as the column names in DataTable
Dim dt As DataTable = ws.ToDataTable(True)
End Sub
End Class
10.2 Bir Excel Dosyasını DataSet'e Nasıl Ayrıştırılır
Tam bir Excel dosyasını bir DataSet'e çözümlemek istiyorsak, bu amaç için IronXL'deki .ToDataSet() fonksiyonunu kullanabiliriz.
class Program
{
static void Main(string[] args)
{
// Load an entire workbook into a DataSet
WorkBook wb = WorkBook.Load("sample.xlsx");
// Convert workbook to DataSet
DataSet ds = wb.ToDataSet();
// We can also get a DataTable from the DataSet which corresponds to a WorkSheet
DataTable dt = ds.Tables[0];
}
}
class Program
{
static void Main(string[] args)
{
// Load an entire workbook into a DataSet
WorkBook wb = WorkBook.Load("sample.xlsx");
// Convert workbook to DataSet
DataSet ds = wb.ToDataSet();
// We can also get a DataTable from the DataSet which corresponds to a WorkSheet
DataTable dt = ds.Tables[0];
}
}
Friend Class Program
Shared Sub Main(ByVal args() As String)
' Load an entire workbook into a DataSet
Dim wb As WorkBook = WorkBook.Load("sample.xlsx")
' Convert workbook to DataSet
Dim ds As DataSet = wb.ToDataSet()
' We can also get a DataTable from the DataSet which corresponds to a WorkSheet
Dim dt As DataTable = ds.Tables(0)
End Sub
End Class
10.3 Belirli Bir Aralıkta Excel Verilerini Okuma
IronXL, belirli bir aralıkta Excel dosya verilerini okuma konusunda akıllı bir yöntem sunar. Aralık, hem satırlara hem de sütunlara uygulanabilir.
class Program
{
static void Main(string[] args)
{
// Load the workbook and access a specific worksheet
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();
}
}
class Program
{
static void Main(string[] args)
{
// Load the workbook and access a specific worksheet
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();
}
}
Friend Class Program
Shared Sub Main(ByVal args() As String)
' Load the workbook and access a specific worksheet
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
End Class
Yukarıdaki kod aşağıdaki çıktıyı görüntüler:
B3:B8 aralığındaki tüm değerleri erişmek için Konsol çıktısı
Ve sample.xlsx Excel dosyasının değerlerini üretir:
sample.xlsx'ten veri gösterimi
Ek olarak, IronXL hücrelerle etkileşimde bulunmak için stil ve kenarlık, matematik işlevleri, koşullu biçimlendirme veya mevcut verilerden grafik oluşturma dahil olmak üzere birçok Excel yöntemiyle de uyumludur.
11. Excel Dosyasında Boolean Verilerini Nasıl Okuruz
Uygulama geliştirmede, Excel dosyalarındaki Boolean veri türüne dayanarak kararlar almamız gerekebilir.
class Program
{
static void Main(string[] args)
{
// Load the workbook and access a specific worksheet
WorkBook wb = WorkBook.Load("sample.xlsx");
WorkSheet ws = wb.GetWorkSheet("Sheet1");
// Traverse a range and output boolean values
foreach (var item in ws["G1:G10"])
{
Console.WriteLine("Condition is: {0}", item.BoolValue);
}
Console.ReadKey();
}
}
class Program
{
static void Main(string[] args)
{
// Load the workbook and access a specific worksheet
WorkBook wb = WorkBook.Load("sample.xlsx");
WorkSheet ws = wb.GetWorkSheet("Sheet1");
// Traverse a range and output boolean values
foreach (var item in ws["G1:G10"])
{
Console.WriteLine("Condition is: {0}", item.BoolValue);
}
Console.ReadKey();
}
}
Friend Class Program
Shared Sub Main(ByVal args() As String)
' Load the workbook and access a specific worksheet
Dim wb As WorkBook = WorkBook.Load("sample.xlsx")
Dim ws As WorkSheet = wb.GetWorkSheet("Sheet1")
' Traverse a range and output boolean values
For Each item In ws("G1:G10")
Console.WriteLine("Condition is: {0}", item.BoolValue)
Next item
Console.ReadKey()
End Sub
End Class
Bundan aldığımız çıktı:
Boolean Verileri elde etmeden Konsol çıktısı
Ve Excel dosyası sample.xlsx, C1'den C10'a kadar olan değerlerle:
Konsol çıktısı ile karşılaştırmak için Excel örneği
12. Tüm Excel Çalışma Sayfasını Okuma
Satır ve sütun dizinlerini kullanarak bir Excel Çalışma Sayfasını tamamen okumak basittir. Bu amaç için, bir satıra özgü tüm sütunları geçmek için bir, tüm satırları taramak için ikinci döngü olmak üzere iki döngü kullanırız. Daha sonra, tüm Excel Çalışma Sayfasındaki tüm hücre değerlerini kolayca elde edebiliriz.
class Program
{
static void Main(string[] args)
{
// Load the workbook and access a specific worksheet
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();
}
}
class Program
{
static void Main(string[] args)
{
// Load the workbook and access a specific worksheet
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();
}
}
Friend Class Program
Shared Sub Main(ByVal args() As String)
' Load the workbook and access a specific worksheet
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
End Class
Tüm değerleri okumak için Konsol çıktısı
13. Interop Olmadan Excel Dosyalarını Okuma
IronXL, geliştiricilerin XLS ve XLSX belgelerinden Excel verilerini okumalarını ve düzenlemelerini Microsoft.Office.Interop.Excel kullanmadan sağlayan bir C# için Excel Kütüphanesi ve .NET'tir.
API, Excel dosyalarını şunlar için sezgisel olarak oluşturmamıza, okumamıza, manipüle etmemize, kaydetmemize ve dışa aktarmamıza izin verir:
- .NET Framework 4.5+
- .NET Core 2+
- .NET Standard
- Xamarin
- Windows Mobile
- Mono
- Azure Bulut Barındırma
- Blazor
- .NET MAUI
Aşağıdaki ad alanlarını ekleyin:
using IronXL;
using System;
using System.Linq;
using IronXL;
using System;
using System.Linq;
Imports IronXL
Imports System
Imports System.Linq
Şimdi ana fonksiyonun içine aşağıdaki kodu yazın.
class Program
{
static void Main(string[] args)
{
// Load an Excel file and access the first worksheet
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);
}
}
}
class Program
{
static void Main(string[] args)
{
// Load an Excel file and access the first worksheet
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);
}
}
}
Friend Class Program
Shared Sub Main(ByVal args() As String)
' Load an Excel file and access the first worksheet
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
End Sub
End Class
Her hücreden konsol çıktısı
IronXL ayrıca ASP.NET, MVC, Windows, macOS, Linux, iOS ve Android Mobil uygulama geliştirmeyi de tamamen destekler.
14. Sonuç ve Iron XL Özel Teklifi
C#'ta CSV ayrıştırmanın yanı sıra, IronXL sadece iki satır kodla CSV dosyalarını Excel'e dönüştürür!
C# veya VB.NET kullanarak, Interop'a ihtiyaç duymadan IronXL'nin Excel API'sini kullanmak çok kolaydır. Excel elektronik tablolarını okuyabilir, düzenleyebilir ve oluşturabilir veya XLS/XLSX/CSV/TSV gibi diğer Excel formatlarıyla çalışabilirsiniz. Birden fazla çerçeve desteği ile, iki ürün fiyatına 5 ürün satın alabilirsiniz. Daha fazla bilgi için fiyatlandırma sayfamıza tıklayın.
Iron Suite'in 5 ürünü
Sıkça Sorulan Sorular
C#'da bir CSV dosyasi nasil okunur?
C#'da bir CSV dosyası okumak için, NuGet aracılığıyla Visual Studio'da kütüphaneyi yükleyerek IronXL'yi kullanabilirsiniz. Yüklendikten sonra, WorkBook.LoadCSV yöntemi ile CSV dosyasını yükleyin ve yorumlayın.
CSV nedir ve C#'da işlemeyi neden karmaşık hale getirebilir?
CSV, basit bir veri formatıdır ancak değişken ayraçlar nedeniyle işlenmesi karmaşık olabilir. IronXL, C# projelerinde CSV dosyalarını okuma ve ayrıştırmayı basitleştirir.
C# kullanarak CSV dosyalarını Excel'e dönüştürebilir miyim?
Evet, IronXL, CSV dosyalarını Excel formatları olan XLS veya XLSX'e dönüştürmenizi sağlar. CSV dosyasını yükleyip WorkBook.SaveAs yöntemi ile kaydederek bu işlemi gerçekleştirebilirsiniz.
C# projesine IronXL'yi nasıl kurarım?
IronXL'yi Visual Studio'da NuGet Paket Yöneticisi'ni kullanarak yükleyebilirsiniz. 'IronXl.Excel' arayarak projeye ekleyin ve Excel dosyaları ile çalışmaya başlayın.
Excel hücre verilerini C#'da belirli veri türlerine ayrıştırmak mümkün mü?
Evet, IronXL ile, Excel hücre değerlerini, Int32Value ve BoolValue gibi yöntemlerle sayısal ve Boolean gibi belirli veri türlerine ayrıştırabilirsiniz.
C# kullanarak Excel sayfasındaki belirli bir hücre aralığındaki verileri nasıl okuyabilirim?
IronXL kullanarak, bir döngü ile aralığı yineleyerek ve IronXL'nin indeksleme yetenekleri aracılığıyla hücre değerlerine erişerek belirli hücrelerden veri okuyabilirsiniz.
Bir Excel çalışma sayfasını C#'da DataTable'a nasıl dönüştürebilirim?
IronXL'nin WorkSheet.ToDataTable yöntemi ile, bir Excel çalışma sayfasını verimli bir şekilde bir DataTable nesnesine ayrıştırarak veri manipülasyonu için dönüştürebilirsiniz.
Excel dosyalarını program yoluyla okumak için Microsoft Office Interop'a ihtiyaçım var mı?
Hayır, IronXL ile, Microsoft Office Interop olmadan Excel dosyalarını okuyabilir ve manipüle edebilirsiniz, bu da bağımsız ve verimli bir çözüm sunar.
Excel ve CSV dosyalarını yönetmek için IronXL kullanmanın avantajları nelerdir?
IronXL, kolay kurulum, Interop'a bağımlılık yok, birden fazla Excel format desteği ve çeşitli .NET çerçeveleriyle uyumluluk sunarak, CSV ve Excel dosyalarını yönetmede verimliliği artırır.
C#'da tam bir Excel çalışma sayfası nasıl okunur?
IronXL kullanarak, tüm satırları ve sütunları dolaşmak ve IronXL'nin yöntemlerini kullanarak hücre değerlerini çıkarmak için iç içe döngüler kullanarak tam bir Excel çalışma sayfası okuyabilirsiniz.




