Altbilgi içeriğine atla
IRONXL KULLANARAK
C# ile IronXL kullanarak CSV dosyaları nasıl okunur

C# CSV Dosyaları Okuma: Bir Eğitim

Çeşitli Excel formatları ile çalışmak genellikle verileri okumak ve ardından programlı olarak yeniden yapılandırmayı gerektirir. Bu makalede, mükemmel bir araç olan IronXL kullanarak C#'da bir CSV dosyasını nasıl okuyacağımızı ve bir Excel elektronik tablosundan veri nasıl çözeceğimizi öğreneceğiz.

CSV Nedir?

CSV basit bir veri formatıdır, ancak birçok farklar olabilir; Çünkü satırlar ve verilerin sütunları arasında ayırıcılar kullanır, C# projelerimizde programlı olarak okumak zor olabilir. Bu makale, CSV dosyalarını okumak için IronXL kütüphanesini nasıl kullanacağı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'den yararlanmadan önce, onu kurmalısınız. İşte hızlı bir walkthrough.

  1. Visual Studio'da, Proje menüsünü seçin
  2. NuGet Paketlerini Yönet
  3. IronXL.Excel'i Arayın
  4. Yükleyin

C#'ta CSV Dosyalarını Okuma: Bir Eğitici, Şekil 1: Visual Studio'da NuGet Paket Yöneticisinde IronXL Arayın Visual Studio'da NuGet Paket Yöneticisinde IronXL'i arayın

C#'da CSV dosyalarını okumanız gerektiğinde, IronXL mükemmel bir araçtır. Virgüller veya aşağıda görülen kod segmentlerinde olduğu gibi herhangi bir başka ayırıcı ile 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")
$vbLabelText   $csharpLabel

Çıktı:

C#'ta CSV Dosyalarını Okuma: Bir Eğitici, Şekil 2: Virgül ayırıcı ile CSV dosyası çıktısı Virgül Ayırıcılı Çıkış CSV Dosyası

Kod Açıklaması:

Bir WorkBook nesnesi oluşturulur. Daha sonra WorkBook nesnesi için LoadCSV yöntemi kullanılarak, CSV'nin adı, formatı ve CSV dosyasında kullanılan ayırıcılar belirtilir. Bu durumda, ayırıcı olarak virgüller kullanılır.

Daha sonra bir WorkSheet nesnesi oluşturulur. CSV dosyasının içeriği buraya yerleştirilecektir. Dosya, yeni bir ad ve format altında kaydedilir.

C#'ta CSV Dosyalarını Okuma: Bir Eğitici, Şekil 3: Microsoft Excel'de Gösterilen Veriler Microsoft Excel'de Görüntülenen Veriler


2. Excel Dosyaları için IronXL

IronXL'i projeniz için kullanarak C#'da Excel dosya formatlarıyla çalışmak için verimli bir yol oluşturabilirsiniz. IronXL'i direkt indirmeyle kurabilirsiniz. Alternatif olarak, Visual Studio için NuGet Kurulumu kullanabilirsiniz. Yazılım geliştirici için ücretsizdir.

dotnet add package IronXL.Excel

3. WorkBook Yükleyin ve WorkSheet Erişin

WorkBook, Excel dosyasına ve tüm işlevlerine tam erişim sağlayan IronXL sınıfıdır. Örneğin, bir Excel dosyasına erişmek istiyorsak, 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
$vbLabelText   $csharpLabel

Excel dosyasının belirli bir ç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
$vbLabelText   $csharpLabel

Excel çalışma sayfası ws elde ettikten sonra, ondan her tür veriyi çıkarabilir ve tüm Excel işlevlerini uygulayabilirsiniz. Excel çalışma sayfası ws'den verilere ş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
$vbLabelText   $csharpLabel

4. Bir Excel Çalışma Sayfasını DataTable Olarak Okumak

IronXL kullanarak, bir Excel WorkSheet'yi bir DataTable gibi kullanmak ç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
$vbLabelText   $csharpLabel

Aşağıdaki ad alanlarını kullanın:

using IronXL;
using System.Data;
using IronXL;
using System.Data;
Imports IronXL
Imports System.Data
$vbLabelText   $csharpLabel

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
$vbLabelText   $csharpLabel

C#'ta CSV Dosyalarını Okuma: Bir Eğitici, Şekil 4: Bir DataTable nesnesinden Konsol çıktısı DataTable Nesnesinden Konsol Çıkışı

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
$vbLabelText   $csharpLabel

C#'ta CSV Dosyalarını Okuma: Bir Eğitici, Şekil 5: DataSet nesnesinden sayfa adını erişim DataSet Nesnesinden Sayfa Adına Erişim

Tüm Excel sayfaları boyunca her hücre değerine nasıl erişileceğini gösteren başka bir ö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
$vbLabelText   $csharpLabel

C#'ta CSV Dosyalarını Okuma: Bir Eğitici, Şekil 6: Dataset nesnesinin Konsol çıktısı DataSet Nesnesinin Konsol Çıktısı

5. C# .NET ile CSV ayrıştırma

CSV dosyalarının, satır sonlarının alanlarda nasıl ele alındığı veya basit bir dize ayırma yaklaşımını tamamen engelleyen tekliflerle kapsanan alanların nasıl işleneceği konusunda bolluğu vardır. C# .NET'te CSV dönüştürürken, değerlere virgülle ayrılmasını yerine özelleştirilebilir bir ayırıcıyı belirterek yakın zamanda şu seçenekleri keşfettim: string.Split(',')

6. C# Kayıtlarında CSV Verilerini Okuma

Bu süreç okuyucuyu bir sonraki dosya boyunca ilerletir. TryGetField'de CSV alan dosyalarını okuruz. CSV dosyalarının alan alanlarında kayıt alanları olarak okuma işlevini kullanırız.

// 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
$vbLabelText   $csharpLabel

C#'ta CSV Dosyalarını Okuma: Bir Eğitici, Şekil 7: DataTable'dan Konsol çıktısı DataTable'dan Konsol Çıkışı

7. Excel Dosyalarından Veri Alma

Artık açık Excel WorkSheet'den çeşitli yöntemler kullanarak her türlü veriyi kolayca edinebiliriz. Aşağıdaki örnekte, belirli bir hücre değerine nasıl erişileceğini ve onu string olarak nasıl ayrıştırılacağını 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()
$vbLabelText   $csharpLabel

Yukarıdaki satırda, ws WorkSheet'dür, adım 2'de tanımlanmıştır. Bu 'basit' bir yaklaşımdır, ancak daha fazla bilgiyi ve Excel dosyası verilerine nasıl erişileceğine dair farklı örnekleri okuyabilirsiniz.

8. How to Parse Excel Files in C

Uygulama oluşturma için Excel Elektronik Tabloları kullanırken, sık sık veriye dayalı olarak sonuçları analiz eder ve doğru sonuçları elde etmek için C# içinde Excel dosya verilerini istenen forma ayrıştırmamız gerekir. Verileri farklı formatlara ayrıştırmak, IronXL kullanarak C# ortamında kolaylaştırılmıştı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
$vbLabelText   $csharpLabel

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. Öncelikle, sayısal Excel verileri ile nasıl başa çıkacağımıza ve ardından bunu istediğimiz formata nasıl ayrıştıracağımıza bakıyoruz.

C#'ta CSV Dosyalarını Okuma: Bir Eğitici, Şekil 8: Her veri türü için özet tablo Her Veri Türü İç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
$vbLabelText   $csharpLabel

Bu kod aşağıdaki çıktıyı görüntüleyecektir:

C#'ta CSV Dosyalarını Okuma: Bir Eğitici, Şekil 9: Doğru veri türü ile Konsol çıktısı Doğru Veri Türü ile Konsol Çıkışı

Ve burada Excel dosyası sample.xlsx'in değerlerini görebiliriz:

C#'ta CSV Dosyalarını Okuma: Bir Eğitici, Şekil 10: Excel'de doğru veri türünü göster Excel'de Doğru Veri Türünü Görüntüleme

Excel dosyası verilerini Boolean veri türüne ayrıştırmak için IronXL, BoolValue işlevini sağlar. Aşağıda görüldüğü 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
$vbLabelText   $csharpLabel

10. Excel Dosyalarını C# Koleksiyonlarına Nasıl Ayrıştırılır

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
$vbLabelText   $csharpLabel

10.1 Bir Excel WorkSheet'i DataTable'a Nasıl Ayrıştırılır

IronXL'un mükemmel bir özelliği, belirli bir Excel WorkSheet'yi kolayca bir DataTable'a dönüştürebilmemizdir. Bu amaçla, IronXL'un .ToDataTable() işlevini aşağıdaki ş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
$vbLabelText   $csharpLabel

10.2 Bir Excel Dosyasını DataSet'e Ayrıştırma

Tam bir Excel dosyasını bir DataSet'e ayrıştırmak istersek, bu amaçla IronXL'deki .ToDataSet() işlevini 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
$vbLabelText   $csharpLabel

10.3 Belirli Bir Aralıkta Excel Verilerini Okuma

IronXL, belirli bir aralıkta Excel dosya verilerini okumak için akıllı bir yöntem sağlar. 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
$vbLabelText   $csharpLabel

Yukarıdaki kod aşağıdaki çıktıyı görüntüler:

C#'ta CSV Dosyalarını Okuma: Bir Eğitici, Şekil 11: B3:B8 aralığındaki tüm değerlere erişim için Konsol çıktısı B3:B8 Aralığındaki Tüm Değerlere Erişmek İçin Konsol Çıkışı

Ve Excel dosyası sample.xlsx değerlerini üretir:

C#'ta CSV Dosyalarını Okuma: Bir Eğitici, Şekil 12: sample.xlsx'ten Veri görüntüleme Sample.xlsx'ten Veri Görüntüleme

Ek olarak, IronXL birçok Excel metodu ile uyumludur ve hücrelerle etkileşime geçirmek için şekillendirme ve kenarlık, matematik fonksiyonları, koşullu biçimlendirme veya mevcut verilerden grafikler oluşturma dahil olmak üzere kullanılabilir.

11. Bir Excel Dosyasında Boolean Veriyi Okuma

Uygulama geliştirmede, Excel dosyalarındaki Boolean veri tipine dayalı olarak kararlar almamız gerekir.

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
$vbLabelText   $csharpLabel

Bundan, elde edilen çıktı şu şekildedir:

C#'ta CSV Dosyalarını Okuma: Bir Eğitici, Şekil 13: Boolean Veri elde etmek için Konsol çıktısı Boolean Veri Alımından Konsol Çıkışı

Ve Excel dosyası sample.xlsx, C1'den C10'a kadar olan değerlerle:

C#'ta CSV Dosyalarını Okuma: Bir Eğitici, Şekil 14: Konsol çıktısı ile karşılaştırmak için Excel örneği Konsol Çıkışı ile Karşılaştırmak için Excel Örneği

12. Tam Excel Çalışma Sayfası Nasıl Okunur

Tam bir Excel Çalışma Sayfasını satır ve sütun indekslerini kullanarak okumak basittir. Bu amaçla, tüm satırları ve belirli bir satırdaki tüm sütunları dolaşmak için iki döngü kullanırız. Sonra, tüm Excel Çalışma Sayfası içindeki 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
$vbLabelText   $csharpLabel

C#'ta CSV Dosyalarını Okuma: Bir Eğitici, Şekil 15: Tüm değerleri okuma için Konsol çıktısı Tüm Değerleri Okumaktan Konsol Çıkışı

13. Interop Olmadan Excel Dosyalarını Okuma

IronXL, geliştiricilerin, XLS ve XLSX Belgelerinden Excel verilerini okumalarını ve düzenlemelerini sağlayan bir Excel Kitaplığıdır ve .NET Microsoft.Office.Interop.Excel kullanmadan çalışır.

API, Excel dosyalarını sezgisel bir şekilde oluşturma, okuma, manipüle etme, kaydetme ve dışa aktarma imkanı sağlar:

  1. .NET Framework 4.5+
  2. .NET Core 2+
  3. .NET Standard
  4. Xamarin
  5. Windows Mobile
  6. Mono
  7. & Azure Cloud Hosting
  8. Blazor
  9. .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
$vbLabelText   $csharpLabel

Aşağıdaki kodu main fonksiyonunun içine yazınız.

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
$vbLabelText   $csharpLabel

C#'ta CSV Dosyalarını Okuma: Bir Eğitici, Şekil 16: Her hücrenin Konsol çıktısı Her hücreden konsol çıktısı

IronXL ayrıca ASP.NET, MVC, Windows, macOS, Linux, iOS ve Android Mobil uygulama geliştirmeyi tam olarak destekler.

14. Sonuç ve IronXL Özel Teklifi

C#'ta CSV ayrıştırmasını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, IronXL'in Excel API'sini Interop gereksinimi olmadan kullanmak çok kolaydır. Excel 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 beş ürün satın alabilirsiniz. Daha fazla bilgi için fiyatlandırma sayfamıza tıklayın.

C#'ta CSV Dosyalarını Okuma: Bir Eğitici, Şekil 17: Iron Suite'in 5 ürünü Iron Suite'in 5 ürünü

Sıkça Sorulan Sorular

C#'da bir CSV dosyasını nasıl okuyabilirim?

C#'da bir CSV dosyasını okumak için IronXL'yi kullanarak kitaplığı Visual Studio üzerinden NuGet ile yükleyebilirsiniz. Yüklendikten sonra, CSV dosyasını yüklemek ve yorumlamak için WorkBook.LoadCSV metodunu kullanın.

CSV nedir ve neden C#'da işlenmesi karmaşık olabilir?

CSV basit bir veri formatıdır ancak değişen sınırlayıcılar nedeniyle işlenmesi karmaşık olabilir. IronXL, C# projelerinde CSV dosyalarını okuma ve yorumlamayı basitleştirir.

CSV dosyalarını C# kullanarak Excel'e dönüştürebilir miyim?

Evet, IronXL, CSV dosyalarını Excel formatlarına (XLS veya XLSX gibi) dönüştürmenize olanak tanır; CSV'yi yükleyip WorkBook.SaveAs metodunu kullanarak kaydedebilirsiniz.

IronXL'yi bir C# projesine nasıl kurarım?

IronXL'yi Visual Studio'da NuGet Paket Yöneticisi'ni kullanarak yükleyebilirsiniz. 'IronXL.Excel' arayın ve proje başladığında Excel dosyalarıyla çalışmak için ekleyin.

Excel hücre verilerini C#'da belirli veri türlerine ayıklayabilir miyim?

Evet, IronXL ile Excel hücre değerlerini Int32Value ve BoolValue gibi yöntemleri kullanarak belirli veri türlerine (sayısal ve Boolean gibi) ayıklayabilirsiniz.

C# kullanarak bir Excel sayfasındaki belirli bir hücre aralığından veri nasıl okunur?

IronXL kullanarak, belirli hücrelerden veri okumak için aralıkta bir döngü ile dolaşarak ve hücre değerlerine IronXL'nin dizinleme yetenekleri aracılığıyla erişebilirsiniz.

Bir Excel çalışma sayfasını C#'da DataTable'ye nasıl dönüştürürüm?

IronXL'nin WorkSheet.ToDataTable metodunu kullanarak bir Excel çalışma sayfasını DataTable'ye dönüştürebilir, böylece verileri manipüle etmek için verimli bir şekilde bir DataTable nesnesine yorumlayabilirsiniz.

Programlı olarak Excel dosyalarını okumak için Microsoft Office Interop'a ihtiyacım var mı?

Hayır, IronXL ile Microsoft Office Interop'a gerek kalmadan Excel dosyalarını okuma ve manipüle edebilirsiniz, bu da onu bağımsız ve verimli bir çözüm yapar.

Excel ve CSV dosyalarını işlemek için IronXL kullanmanın avantajları nelerdir?

IronXL, kolay kurulumu, Interop'a bağımlılığı olmaması, birden fazla Excel formatını desteklemesi ve farklı .NET çerçeveleri ile uyumluluğu ile CSV ve Excel dosyalarını işleme üretkenliğini artırır.

Bir Excel çalışma sayfasını C#'da nasıl tamamen okurum?

IronXL kullanarak tam bir Excel çalışma sayfasını okumak için, tüm satırları ve sütunları dolaşmak için iç içe döngüler kullanabilir ve hücre değerlerini almak için IronXL'nin yöntemlerini kullanabilirsiniz.

Curtis Chau
Teknik Yazar

Curtis Chau, Bilgisayar Bilimleri alanında Lisans Derecesine (Carleton Üniversitesi) sahip ve Node.js, TypeScript, JavaScript ve React konularında uzmanlaşmış ön uç geliştirmeyle ilgileniyor. Sezgisel ve estetik açıdan hoş kullanıcı arayüzleri oluşturma tutkunu, Curtis modern çerçevelerle çalışmayı ve iyi yapı...

Daha Fazla Oku

Iron Destek Ekibi

Haftada 5 gün, 24 saat çevrimiçiyiz.
Sohbet
E-posta
Beni Ara