在 C#中讀取 CSV 文件:教程
處理多種Excel格式通常需要讀取資料,然後以程式方式重新配置。 在本文中,我們將學習如何使用IronXL程式庫讀取CSV文件並從Excel試算表中解析資料。
什麼是CSV?
CSV是一種簡單的資料格式,但可能存在多種差異; 由於它使用多種分隔符來區分資料的行和列,在我們的C#專案中程式化讀取會很困難。 本文將向您展示如何使用IronXL程式庫來讀取CSV文件。
1. How to read a CSV File in C
在使用IronXL讀取MVC、ASP.NET或.NET Core中的CSV文件之前,您需要安裝它。 以下是快速指南。
- 在Visual Studio中選擇專案選單
- 管理NuGet套件
- 搜尋IronXL.Excel
- 安裝
在Visual Studio中的NuGet套件管理器中搜尋IronXL
當您需要在C#中讀取CSV文件時,IronXL是理想的工具。 您可以使用下列程式碼段中顯示的方式來讀取帶逗號或任何其他分隔符的CSV文件。
// 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")
輸出:
帶逗號分隔符的輸出CSV文件
程式碼解釋:
建立了一個WorkBook物件。 然後,使用WorkBook物件的LoadCSV方法來指定CSV的名稱、格式以及正在讀取的CSV文件中使用的分隔符。 在這種情況下,以逗號作為分隔符。
然後建立WorkSheet物件。 CSV文件的內容將放置在這裡。 文件以新的名稱和格式保存。
在Microsoft Excel中顯示資料
2. 用於Excel文件的IronXL
在您的專案中使用IronXL,這是一種在C#中處理Excel文件格式的簡化方式。 您可以通過直接下載安裝IronXL。 或者,您也可以使用Visual Studio的NuGet安裝。 軟體供免費開發使用。
dotnet add package IronXL.Excel
3. 載入WorkSheet
WorkBook是IronXL的類,其物件提供對Excel文件及其功能的完整存取。 例如,如果我們想存取Excel文件,我們會使用程式碼:
// 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
要存取Excel文件的特定工作表,IronXL提供了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
獲得Excel工作表ws後,您可以從中提取任何型別的資料並對其執行所有Excel功能。 可以通過此過程從Excel工作表ws存取資料:
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. 將Excel工作表讀取為DataTable
使用IronXL,將Excel WorkSheet作為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
使用以下命名空間:
using IronXL;
using System.Data;
using IronXL;
using System.Data;
Imports IronXL
Imports System.Data
請撰寫以下程式碼:
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
DataTable物件的控制台輸出
在此範例中,我們將看看如何使用Excel文件作為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
從DataSet物件存取工作表名稱
我們來看看另一個範例,了解如何存取所有Excel工作表的每個單元格值。 在這裡,我們可以存取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
資料集物件的控制台輸出
5. 在C# .NET中解析CSV
CSV文件在字段中處理換行符或字段可以用引號括起來的情況下會有許多問題,這會完全阻止簡單的字串拆分方法。 我最近發現了以下選項,可以在C#.NET中通過指定可自定義分隔符來轉換CSV,而不是使用string.Split(',')以逗號分隔值。
6. 在C#記錄中讀取CSV資料
此過程使讀取器前進到下一個文件。我們在TryGetField中讀取CSV字段文件。 我們在CSV文件的字段字段上使用讀取功能作為記錄字段。
// 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的控制台輸出
7. 從Excel文件中獲取資料
現在我們可以使用多種方法輕鬆地從打開的Excel WorkSheet中獲取任何型別的資料。 在下面的範例中,我們可以看到如何存取特定單元格值並將其解析為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()
在上面的行中,WorkSheet,在第2步中已定義。這是'簡單的'方法,但您可以閱讀更多並看到不同的範例,了解如何存取Excel文件資料。
8. How to Parse Excel Files in C
在應用程式構建中使用Excel試算表時,我們通常會根據資料分析結果,並需要在C#中將Excel文件資料解析為所需格式,以獲得正確的結果。 在C#環境中使用IronXL,將資料解析為不同格式變得容易; 請參見下面的步驟。
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資料解析為數字和布林值
現在我們轉向如何解析Excel文件資料。 首先,我們看看如何處理數字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");
// 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
此程式碼將顯示以下輸出:
具有正確資料型別的控制台輸出
我們可以在這裡看到Excel文件sample.xlsx的值:
在Excel中顯示正確的資料型別
要將Excel文件資料解析為布林資料型別,IronXL提供BoolValue功能。 它可以這樣使用:
// 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文件解析到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
10.1 如何將Excel WorkSheet解析為DataTable
IronXL的一個優秀特性是我們可以輕鬆將特定的Excel WorkSheet轉換為DataTable。 為此目的,我們可以使用IronXL的.ToDataTable()功能如下:
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 如何將Excel文件解析為DataSet
如果我們想將完整的Excel文件解析為DataSet,則可以使用IronXL中的.ToDataSet()功能來完成此目的。
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 在特定範圍內讀取Excel資料
IronXL提供了一種智能方法來讀取特定範圍內的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");
// 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
上述程式碼顯示了以下輸出:
控制台輸出以存取範圍B3:B8中的所有值
並產生Excel文件sample.xlsx的值:
從sample.xlsx顯示資料
此外,IronXL也相容許多Excel方法,以與單元格進行互動,包括樣式和邊框,數學函式,條件格式化或從可用資料建立圖表。
11. 如何讀取Excel文件中的布林資料
在應用程式開發中,我們需要根據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
從這裡,我們獲得輸出:
從獲取布林資料中獲得的控制台輸出
以及Excel文件sample.xlsx中從C1到C10的值:
Excel樣本與控制台輸出進行比較
12. 如何讀完整的Excel工作表
使用行和列索引讀取完整的Excel工作表非常簡單。 為此目的,我們使用兩個迴圈:一個用於遍歷所有行,另一個用於遍歷特定行的所有列。 然後我們可以輕鬆獲得整個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
讀取所有值的控制台輸出
13. 如何不使用Interop讀取Excel文件
IronXL是一個C#和.NET的Excel程式庫,允許開發人員從XLS和XLSX文件讀取和編輯Excel資料而不使用Microsoft.Office.Interop.Excel。
該API允許我們以直觀的方式建立、讀取、操作、保存和匯出Excel文件,支持:
- .NET Framework 4.5+
- .NET Core 2+
- .NET Standard
- Xamarin
- Windows Mobile
- Mono 7.& Azure雲托管
- Blazor
- .NET MAUI
新增以下命名空間:
using IronXL;
using System;
using System.Linq;
using IronXL;
using System;
using System.Linq;
Imports IronXL
Imports System
Imports System.Linq
現在在主函式中撰寫以下程式碼。
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
每個單元格的控制台輸出
IronXL還完全支持ASP.NET、MVC、Windows、macOS、Linux、iOS和Android移動應用程式開發。
14. 結論和IronXL特別優惠
除了在C#中解析CSV外,IronXL只需兩行程式碼即可將CSV文件轉換為Excel!
使用C#或VB.NET,使用IronXL的Excel API非常簡單,無需Interop。您可以讀取、編輯、建立Excel試算表或處理其他Excel格式,如XLS/XLSX/CSV/TSV。 在多框架支持的情況下,您可以以兩款產品的價格購買五款產品。 點擊我們的定價頁面以獲取更多資訊。
Iron Suite的5款產品
常見問題
如何在C#中讀取CSV文件?
要在C#中讀取CSV文件,您可以透過Visual Studio中的NuGet安裝IronXL程式庫。安裝後,使用WorkBook.LoadCSV方法載入並解釋CSV文件。
什麼是CSV,為什麼在C#中處理它會很複雜?
CSV是一種簡單的資料格式,但由於分隔符多樣處理可能會很複雜。IronXL簡化了在C#項目中讀取和解析CSV文件。
我可以使用C#將CSV文件轉換為Excel嗎?
可以,IronXL允許您將CSV文件轉換為XLS或XLSX等Excel格式,通過載入CSV並使用WorkBook.SaveAs方法保存。
如何在C#項目中安裝IronXL?
您可以使用Visual Studio中的NuGet套件管理器安裝IronXL。搜尋'IronXL.Excel'並將其新增到您的專案中,以開始處理Excel文件。
是否可以在C#中將Excel單元格資料解析為特定的資料型別?
可以,使用IronXL,您可以將Excel單元格值解析為特定的資料型別,例如通過Int32Value和BoolValue方法的數值和布林值。
如何使用C#從Excel表中的特定範圍讀取資料?
使用IronXL,您可以通過迭代該範圍並透過IronXL的索引功能存取單元格值來從特定單元格讀取資料。
如何在C#中將Excel工作表轉換為DataTable?
您可以使用IronXL的WorkSheet.ToDataTable方法將Excel工作表轉換為DataTable,該方法可以有效地將工作表解析為DataTable物件,以便於資料操作。
我需要Microsoft Office Interop來以程式方式讀取Excel文件嗎?
不需要,使用IronXL,您可以在不需要Microsoft Office Interop的情況下讀取和操作Excel文件,這使它成為獨立而高效的解決方案。
使用IronXL處理Excel和CSV文件的優勢是什麼?
IronXL提供了簡單的安裝,不依賴於Interop,支援多種Excel格式,並與各種.NET框架相容,提高了處理CSV和Excel文件的生產力。
如何在C#中讀取完整的Excel工作表?
要使用IronXL讀取完整的Excel工作表,您可以使用巢狀迴圈遍歷所有行和列並使用IronXL的方法提取單元格值。




