Przejdź do treści stopki
KORZYSTANIE Z IRONXL
Jak odczytywać pliki CSV w języku C# przy użyciu IronXL

Odczyt plików CSV w C#: samouczek

Praca z różnymi formatami Excel często wymaga odczytywania danych i ich programowej rekonfiguracji. W tym artykule nauczymy się, jak odczytywać plik CSV i analizować dane z arkusza kalkulacyjnego Excel w C# używając IronXL, idealnego narzędzia do tego zadania.

Co to jest CSV?

CSV to proste format danych, ale mogą występować wiele różnic; może być trudne do odczytania programowo w naszych projektach C#, ponieważ używa kilku separatorów do rozróżniania między wierszami a kolumnami danych. Ten artykuł pokaże, jak używać biblioteki IronXL do odczytu plików CSV.


1. How to read a CSV File in C

Zanim będziesz mógł korzystać z IronXL do odczytu plików CSV w MVC, ASP.NET lub .NET Core, musisz go zainstalować. Oto szybkie przeprowadzenie.

  1. W Visual Studio wybierz menu Projekt
  2. Zarządzaj Pakietami NuGet
  3. Wyszukaj IronXL.Excel
  4. Zainstaluj

Reading CSV Files in C#: a Tutorial, Figure 1: Search for IronXL in NuGet Package Manager in Visual Studio Wyszukaj IronXL w Menedżerze pakietów NuGet w Visual Studio

Kiedy potrzebujesz odczytać pliki CSV w C#, IronXL jest idealnym narzędziem. Można odczytać plik CSV z przecinkami lub dowolnym innym separatorem, jak pokazano poniżej w segmentach kodu.

// 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

Wynik:

Reading CSV Files in C#: a Tutorial, Figure 2: Output CSV file with comma delimiter Wyjście pliku CSV z separatorem przecinka

Objaśnienie kodu:

A WorkBook object is created. Metoda LoadCSV dla obiektu WorkBook jest następnie używana do zdefiniowania nazwy pliku CSV, jego formatu oraz separatorów używanych w odczytywanym pliku CSV. W tym przypadku przecinki są używane jako separatory.

Następnie tworzony jest obiekt WorkSheet. To tutaj zostanie umieszczona zawartość pliku CSV. Plik jest zapisywany pod nową nazwą i w nowym formacie.

Reading CSV Files in C#: a Tutorial, Figure 3: Data displayed in Microsoft Excel Dane wyświetlone w Microsoft Excel


2. IronXL dla plików Excel

Użyj IronXL w swoim projekcie, aby w prosty sposób pracować z formatami plików Excel w C#. Możesz zainstalować IronXL poprzez bezpośrednie pobranie. Alternatywnie możesz użyć Instalacji NuGet dla Visual Studio. Oprogramowanie jest darmowe do celów rozwojowych.

dotnet add package IronXL.Excel

3. Załaduj WorkBook i uzyskaj dostęp do WorkSheet

WorkBook to klasa IronXL, której obiekt zapewnia pełny dostęp do pliku Excel i wszystkich jego funkcji. Na przykład, jeśli chcemy odczytać plik Excel, używamy kodu:

// 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

Aby uzyskać dostęp do konkretnego arkusza pliku Excel, IronXL dostarcza klasę WorkSheet.

// 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

Po uzyskaniu arkusza Excel ws, można z niego wydobyć dowolny rodzaj danych i wykonywać na nim wszystkie funkcje Excela. Dostęp do danych z arkusza Excel ws odbywa się w następujący sposób:

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. Odczytywanie arkusza Excel jako DataTable

Korzystając z IronXL, jest bardzo łatwo operować na arkuszu Excel WorkSheet jako DataTable.

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

Użyj następujących przestrzeni nazw:

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

Napisz następujący kod:

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

Reading CSV Files in C#: a Tutorial, Figure 4: Console output from a DataTable object Wyjście konsoli z obiektu DataTable

W tym przykładzie przyjrzymy się, jak używać pliku Excel jako DataSet.

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

Reading CSV Files in C#: a Tutorial, Figure 5: Access sheet name from DataSet object Uzyskaj nazwę arkusza z obiektu DataSet

Przyjrzyjmy się innemu przykładowi, jak uzyskać wartość każdej komórki na wszystkich arkuszach Excel. Tutaj możemy uzyskać wartość każdej komórki na każdym arkuszu w pliku Excel.

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

Reading CSV Files in C#: a Tutorial, Figure 6: Console output of Dataset object Wyjście konsoli z obiektu Dataset

5. Parsowanie CSV w C# .NET

Pliki CSV mają mnóstwo problemów z tym, jak są obsługiwane łamanie linii w polach, lub jak pola mogą być ujęte w cudzysłowy, które całkowicie blokują podejście prostego rozdzielania stringów. Niedawno odkryłem następujące opcje przy konwersji CSV w C# .NET poprzez określenie dostosowywanego separatora zamiast użycia string.Split(',') do oddzielania wartości przecinkiem.

6. Odczyt danych CSV jako rekordów C

Ten proces przesuwa czytnik do kolejnego pliku. Odczytujemy pliki pól CSV w TryGetField. Używamy funkcji odczytu na polach pól plików CSV jako rekordów.

// 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

Reading CSV Files in C#: a Tutorial, Figure 7: Console output from DataTable Wyjście konsoli z DataTable

7. Pobieranie danych z plików Excel

Teraz możemy łatwo uzyskać dowolny rodzaj danych, korzystając z różnych metod, z otwartego arkusza Excel WorkSheet. W poniższym przykładzie możemy zobaczyć, jak uzyskać dostęp do konkretnej wartości komórki i przekonwertować ją na string:

// Access the data by cell addressing
string val = ws["Cell Address"].ToString();
// Access the data by cell addressing
string val = ws["Cell Address"].ToString();
' Access the data by cell addressing
Dim val As String = ws("Cell Address").ToString()
$vbLabelText   $csharpLabel

W powyższej linii ws jest WorkSheet, który został zdefiniowany w Kroku 2. Jest to 'proste' podejście, ale można przeczytać więcej i zobaczyć różne przykłady jak uzyskać dostęp do danych pliku Excel.

8. How to Parse Excel Files in C

Podczas używania arkuszy kalkulacyjnych Excel do budowy aplikacji często analizujemy wyniki na podstawie danych i musimy parsować dane z pliku Excel w C# na wymagany format, aby uzyskać odpowiednie wyniki. Parsowanie danych na różne formaty jest łatwe w środowisku C# przy użyciu IronXL; zobacz poniższe kroki.

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. Jak parsować dane Excel na wartości numeryczne i logiczne

Teraz przechodzimy do tego, jak parsować dane pliku Excel. Najpierw przyjrzymy się, jak radzić sobie z danymi liczbowymi Excel, a następnie jak przekształcić je w nasz wymagany format.

Reading CSV Files in C#: a Tutorial, Figure 8: Summary table for each data type Tabela pod summująca dla każdego typu danych

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

Ten kod wyświetli następujące wyjście:

Reading CSV Files in C#: a Tutorial, Figure 9: Console output with correct data type Wyjście konsoli z poprawnym typem danych

I możemy zobaczyć wartości z pliku Excel sample.xlsx tutaj:

Reading CSV Files in C#: a Tutorial, Figure 10: Display correct data type in Excel Wyświetlenie poprawnego typu danych w Excel

Aby przekonwertować dane z pliku Excel na typ danych Boolean, IronXL dostarcza funkcję BoolValue. Można to użyć w następujący sposób:

// 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. Jak parsować pliki Excel do kolekcji C

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 Jak przekonwertować WorkSheet Excela na DataTable

Jedną z doskonałych funkcji IronXL jest to, że możemy łatwo przekonwertować konkretny WorkSheet Excela na DataTable. Do tego celu możemy użyć funkcji .ToDataTable() IronXL, jak poniżej:

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 Jak parsować plik Excel do DataSet

Jeśli chcemy przekonwertować cały plik Excel na DataSet, to do tego celu możemy użyć funkcji .ToDataSet() w IronXL.

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 Odczytywanie danych Excel w określonym zakresie

IronXL dostarcza inteligentnej metody do odczytywania danych z pliku Excel w określonym zakresie. Zakres można zastosować zarówno do wierszy, jak i kolumn.

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

Powyższy kod wyświetla następujący wynik:

Reading CSV Files in C#: a Tutorial, Figure 11: Console output to access all values in range B3:B8 Wyjście konsoli do uzyskania dostępu do wszystkich wartości w zakresie B3:B8

I generuje wartości z pliku Excel sample.xlsx:

Reading CSV Files in C#: a Tutorial, Figure 12: Data display from sample.xlsx Wyświetlane dane z sample.xlsx

Ponadto, IronXL jest również kompatybilny z wieloma metodami Excel do interakcji z komórkami, w tym stylowaniem i obramowaniem, funkcjami matematycznymi, formatowaniem warunkowym lub tworzeniem wykresów z dostępnych danych.

11. Jak odczytać dane logiczne w pliku Excel

W procesie tworzenia aplikacji musimy podejmować decyzje oparte na typie danych logicznych w plikach Excel.

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

Z tego uzyskujemy wyjście:

Reading CSV Files in C#: a Tutorial, Figure 13: Console output from getting Boolean Data Wyjście konsoli z pobierania danych logicznych

I plik Excel sample.xlsx z wartościami od C1 do C10:

Reading CSV Files in C#: a Tutorial, Figure 14: Excel sample to compare with Console output Próbka Excel do porównania z wyjściem konsoli

12. Jak odczytać kompletny arkusz Excel

Jest prosto odczytać cały arkusz Excel, korzystając z indeksów wierszy i kolumn. Dla tego celu używamy dwóch pętli: jednej do przechodzenia przez wszystkie wiersze, a drugiej do przechodzenia przez wszystkie kolumny określonego wiersza. Następnie możemy łatwo uzyskać wszystkie wartości komórek w całym arkuszu Excel.

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

Reading CSV Files in C#: a Tutorial, Figure 15: Console output from reading all values Wyjście konsoli z odczytywania wszystkich wartości

13. Jak odczytywać pliki Excel bez Interopa

IronXL jest biblioteką Excel dla C# i .NET, która umożliwia deweloperom odczyt i edycję danych z dokumentów XLS i XLSX bez użycia Microsoft.Office.Interop.Excel.

API pozwala nam intuicyjnie tworzyć, odczytywać, manipulować, zapisywać i eksportować pliki Excel dla:

  1. .NET Framework 4.5+
  2. .NET Core 2+
  3. .NET Standard
  4. Xamarin
  5. Windows Mobile
  6. Mono
  7. i Azure Cloud Hosting
  8. Blazor
  9. .NET MAUI

Dodaj następujące przestrzenie nazw:

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

Teraz napisz następujący kod w głównej funkcji.

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

Reading CSV Files in C#: a Tutorial, Figure 16: Console output from each cell Wyjście konsoli z każdej komórki

IronXL również w pełni wspiera aplikacje ASP.NET, MVC, Windows, macOS, Linux, iOS oraz Android Mobile.

14. Podsumowanie i specjalna oferta IronXL

Oprócz parsowania CSV w C#, IronXL konwertuje pliki CSV do Excel w zaledwie dwóch liniach kodu!

Korzystając z C# lub VB.NET, bardzo łatwo jest używać API Excel IronXL bez potrzeby Interopa. Możesz odczytywać, edytować i tworzyć arkusze Excel lub pracować z innymi formatami Excel takimi jak XLS/XLSX/CSV/TSV. Z wsparciem dla wielu frameworków, możesz kupić 5 produktów w cenie dwóch. Kliknij na naszą stronę cenową po więcej informacji.

Reading CSV Files in C#: a Tutorial, Figure 17: 5 products of Iron Suite 5 products of Iron Suite

Często Zadawane Pytania

Jak odczytać plik CSV w języku C#?

Aby przeczytac plik CSV w C#, można uzyc IronXL poprzez zainstalowanie biblioteki za pomoca NuGet w Visual Studio. Po zainstalowaniu, uzyj metody WorkBook.LoadCSV, aby załadować i zinterpretowac plik CSV.

Czym jest CSV i dlaczego może być skomplikowany do obsługi w C#?

CSV to prosty format danych, ale może być skomplikowany do obsługi z powodu różnych delimiterow. IronXL upraszcza czytanie i parsowanie plików CSV w projektach C#.

Czy mogę konwertować pliki CSV na Excel za pomoca C#?

Tak, IronXL pozwala na konwertowanie plików CSV na formaty Excel, takie jak XLS lub XLSX, poprzez zaladowanie CSV i zapisanie za pomoca metody WorkBook.SaveAs.

Jak zainstalować IronXL w projekcie C#?

Możesz zainstalować IronXL używając Menadzera Pakietow NuGet w Visual Studio. Wyszukaj 'IronXL.Excel' i dodaj go do projektu, aby zaczac pracowac z plikami Excel.

Czy możliwe jest sparsowanie danych komorek Excel na specyficzne typy danych w C#?

Tak, z IronXL, można sparsowac wartosci komorek Excel na specyficzne typy danych, takie jak numeryczne i Booleanowe, używając metod jak Int32Value i BoolValue.

Jak mogę przeczytac dane z okreslonego zakresu komorek w arkuszu Excel używając C#?

Używając IronXL, można odczytywać dane z okreslonych komorek, iterujac przez zakres za pomoca pętli i uzyskujac dostep do wartosci komorek przez funkcje indeksowania IronXL.

Jak przeksztalcic arkusz Excel w DataTable w C#?

Można przeksztalcic arkusz Excel w DataTable za pomoca metody IronXL WorkSheet.ToDataTable, która wydajnie parsuje arkusz do obiektu DataTable w celu manipulacji danymi.

Czy potrzebuje Microsoft Office Interop do programowego czytania plików Excel?

Nie, z IronXL, można czytac i manipulowac plikami Excel bez potrzeby Microsoft Office Interop, co czyni go niezależna i wydajna rozwiązania.

Jakie sa zalety używania IronXL do obsługi plików Excel i CSV?

IronXL oferuje łatwa instalacje, brak zależności od Interop, wsparcie dla wielu formatow Excel i kompatybilnosc z różnymi frameworkami .NET, zwiększając produktywnosc w obsludze plików CSV i Excel.

Jak przeczytac caly arkusz Excel w C#?

Aby przeczytac caly arkusz Excel korzystając z IronXL, można uzyc zagniezdzonych pętli, aby przejsc przez wszystkie wiersze i kolumny oraz wyciagnac wartosci komorek korzystając z metod IronXL.

Curtis Chau
Autor tekstów technicznych

Curtis Chau posiada tytuł licencjata z informatyki (Uniwersytet Carleton) i specjalizuje się w front-endowym rozwoju, z ekspertką w Node.js, TypeScript, JavaScript i React. Pasjonuje się tworzeniem intuicyjnych i estetycznie przyjemnych interfejsów użytkownika, Curtis cieszy się pracą z nowoczesnymi frameworkami i tworzeniem dobrze zorganizowanych, atrakcyjnych wizualnie podrę...

Czytaj więcej

Zespół wsparcia Iron

Jesteśmy online 24 godziny, 5 dni w tygodniu.
Czat
E-mail
Zadzwoń do mnie