C# Excel 互通解決方法
許多專案都使用 Excel 來進行清晰的溝通,但如果您使用的是Microsoft.Office.Interop.Excel ,那麼您很可能已經遇到許多複雜的程式碼行。 在本教學中,我們將使用 IronXL 作為 C# Excel Interop 的變通方案,這樣您就不必使用 Interop 來完成您的專案。 您可以使用 C# 程式設計來使用 Excel 檔案資料、建立 Excel 檔案、編輯和操作所有資料。
C# Excel 無互通性
- 下載 Excel 無互通庫
- 使用 C# 存取 Excel 文件
- 建立一個新的 Excel 檔案並透過程式插入數據
- 修改現有檔案、更新和替換儲存格值、刪除行等等
如何替代使用 Excel Interop
- 安裝 Excel 庫以處理 Excel 檔案。
- 開啟
Workbook並新增目前 Excel 檔案。 - 設定預設工作表。
- 從 Excel 工作簿中讀取值。
- 處理並顯示該值。
步驟 1
1. 下載 IronXL 庫
下載 IronXL 庫或使用 NuGet 安裝即可免費使用該庫,然後按照本教學的步驟操作,學習如何在不使用 Interop 的情況下使用 Excel。如果您想將項目正式發布,可以購買相應的許可證。
Install-Package IronXL.Excel
操作指南
2. 存取 Excel 文件數據
為了開發商業應用程序,我們需要能夠輕鬆、完美地存取 Excel 文件中的數據,並能夠根據各種要求以程式設計方式操作這些數據。 使用 IronXL 時,可以使用WorkBook.Load()函數,該函數允許讀取特定的 Excel 檔案。
存取工作簿後,您可以使用WorkBook.GetWorkSheet()函數選擇特定的工作表。 現在您已擁有所有Excel檔案資料。 以下範例展示了我們如何在 C# 專案中使用這些函數來取得 Excel 檔案資料。
// Import the IronXL library to access its functionality
using IronXL;
static void Main(string[] args)
{
// Access Excel file
WorkBook wb = WorkBook.Load("sample.xlsx");
// Access WorkSheet of Excel file
WorkSheet ws = wb.GetWorkSheet("Sheet1");
// Get a specific cell value, convert it to a string, and print it
string a = ws["A5"].Value.ToString();
Console.WriteLine("Getting Single Value:\n\n Value of Cell A5: {0}", a);
Console.WriteLine("\nGetting Many Cells Value using Loop:\n");
// Get multiple cell values using range function and iterate through them
foreach (var cell in ws["B2:B10"])
{
Console.WriteLine(" Value is: {0}", cell.Text);
}
Console.ReadKey(); // Pause the console to view output
}// Import the IronXL library to access its functionality
using IronXL;
static void Main(string[] args)
{
// Access Excel file
WorkBook wb = WorkBook.Load("sample.xlsx");
// Access WorkSheet of Excel file
WorkSheet ws = wb.GetWorkSheet("Sheet1");
// Get a specific cell value, convert it to a string, and print it
string a = ws["A5"].Value.ToString();
Console.WriteLine("Getting Single Value:\n\n Value of Cell A5: {0}", a);
Console.WriteLine("\nGetting Many Cells Value using Loop:\n");
// Get multiple cell values using range function and iterate through them
foreach (var cell in ws["B2:B10"])
{
Console.WriteLine(" Value is: {0}", cell.Text);
}
Console.ReadKey(); // Pause the console to view output
}' Import the IronXL library to access its functionality
Imports Microsoft.VisualBasic
Imports IronXL
Shared Sub Main(ByVal args() As String)
' Access Excel file
Dim wb As WorkBook = WorkBook.Load("sample.xlsx")
' Access WorkSheet of Excel file
Dim ws As WorkSheet = wb.GetWorkSheet("Sheet1")
' Get a specific cell value, convert it to a string, and print it
Dim a As String = ws("A5").Value.ToString()
Console.WriteLine("Getting Single Value:" & vbLf & vbLf & " Value of Cell A5: {0}", a)
Console.WriteLine(vbLf & "Getting Many Cells Value using Loop:" & vbLf)
' Get multiple cell values using range function and iterate through them
For Each cell In ws("B2:B10")
Console.WriteLine(" Value is: {0}", cell.Text)
Next cell
Console.ReadKey() ' Pause the console to view output
End Sub這段程式碼將產生以下結果:
Excel 文件內容如下:
我們可以看到,我們的 Excel 檔案sample.xlsx的A5儲存格中包含small business 。 B2到B10的其他值相同,並顯示在輸出中。
數據集和數據表
我們也可以使用這些說明將 Excel 檔案作為資料集和資料表進行處理。
// Access WorkBook and WorkSheet
WorkBook wb = WorkBook.Load("sample.xlsx");
WorkSheet ws = wb.GetWorkSheet("Sheet1");
// Convert workbook to DataSet
DataSet ds = wb.ToDataSet();
// Convert worksheet to DataTable
DataTable dt = ws.ToDataTable(true);// Access WorkBook and WorkSheet
WorkBook wb = WorkBook.Load("sample.xlsx");
WorkSheet ws = wb.GetWorkSheet("Sheet1");
// Convert workbook to DataSet
DataSet ds = wb.ToDataSet();
// Convert worksheet to DataTable
DataTable dt = ws.ToDataTable(true);' Access WorkBook and WorkSheet
Dim wb As WorkBook = WorkBook.Load("sample.xlsx")
Dim ws As WorkSheet = wb.GetWorkSheet("Sheet1")
' Convert workbook to DataSet
Dim ds As DataSet = wb.ToDataSet()
' Convert worksheet to DataTable
Dim dt As DataTable = ws.ToDataTable(True)您可以閱讀更多關於如何使用Excel 資料集和資料表的內容,其中提供了更多程式碼範例和流程說明。
現在,我們將看到另一個方面,即在我們的 C# 專案中建立一個新的 Excel 檔案。
3. 建立新的 Excel 文件
我們可以輕鬆地在 C# 專案中建立一個新的 Excel 電子表格,並透過程式設計方式向其中插入資料。 為了實現這一目標,IronXL 提供了WorkBook.Create()函數,該函數會建立一個新的 Excel 檔案。
然後我們可以使用WorkBook.CreateWorkSheet()函數來建立所需數量的工作表。
之後,我們還可以插入數據,如下例所示:
// Import the IronXL library
using IronXL;
static void Main(string[] args)
{
// Create a new WorkBook
WorkBook wb = WorkBook.Create();
// Create a new WorkSheet in the workbook
WorkSheet ws = wb.CreateWorkSheet("sheet1");
// Insert data into cells
ws["A1"].Value = "New Value A1";
ws["B2"].Value = "New Value B2";
// Save the newly created Excel file
wb.SaveAs("NewExcelFile.xlsx");
}// Import the IronXL library
using IronXL;
static void Main(string[] args)
{
// Create a new WorkBook
WorkBook wb = WorkBook.Create();
// Create a new WorkSheet in the workbook
WorkSheet ws = wb.CreateWorkSheet("sheet1");
// Insert data into cells
ws["A1"].Value = "New Value A1";
ws["B2"].Value = "New Value B2";
// Save the newly created Excel file
wb.SaveAs("NewExcelFile.xlsx");
}' Import the IronXL library
Imports IronXL
Shared Sub Main(ByVal args() As String)
' Create a new WorkBook
Dim wb As WorkBook = WorkBook.Create()
' Create a new WorkSheet in the workbook
Dim ws As WorkSheet = wb.CreateWorkSheet("sheet1")
' Insert data into cells
ws("A1").Value = "New Value A1"
ws("B2").Value = "New Value B2"
' Save the newly created Excel file
wb.SaveAs("NewExcelFile.xlsx")
End Sub上述程式碼將建立一個名為NewExcelFile.xlsx的新 Excel 文件,並在儲存格位址A1和B2中分別插入值為New Value A1和New Value B2新資料。 透過這種設置,您可以根據需要以相同的方式插入資料。
注意:如果您要建立新的 Excel 文件或修改現有文件,請不要忘記儲存文件,如上面的範例所示。
深入了解如何使用 C# 建立新的 Excel 電子表格,並在您的專案中嘗試程式碼。
4. 修改現有 Excel 文件
我們可以透過程式設計方式修改現有的 Excel 文件,並將更新的資料插入其中。 在修改Excel檔案時,我們將看到以下幾個方面:
- 更新儲存格值
- 將舊值替換為新值
- 刪除行或列
讓我們看看如何在我們的 C# 專案中實現以上主題。
更新單元格值
更新現有Excel電子表格中的儲存格值非常簡單。 只需在專案中開啟 Excel 檔案並指定其工作表,然後按照以下範例所示更新其資料:
// Import the IronXL library
using IronXL;
static void Main(string[] args)
{
// Access the WorkBook and WorkSheet
WorkBook wb = WorkBook.Load("sample.xlsx");
WorkSheet ws = wb.GetWorkSheet("Sheet1");
// Update A3 cell value
ws["A3"].Value = "New Value of A3";
// Save the updated Excel file
wb.SaveAs("sample.xlsx");
}// Import the IronXL library
using IronXL;
static void Main(string[] args)
{
// Access the WorkBook and WorkSheet
WorkBook wb = WorkBook.Load("sample.xlsx");
WorkSheet ws = wb.GetWorkSheet("Sheet1");
// Update A3 cell value
ws["A3"].Value = "New Value of A3";
// Save the updated Excel file
wb.SaveAs("sample.xlsx");
}' Import the IronXL library
Imports IronXL
Shared Sub Main(ByVal args() As String)
' Access the WorkBook and WorkSheet
Dim wb As WorkBook = WorkBook.Load("sample.xlsx")
Dim ws As WorkSheet = wb.GetWorkSheet("Sheet1")
' Update A3 cell value
ws("A3").Value = "New Value of A3"
' Save the updated Excel file
wb.SaveAs("sample.xlsx")
End Sub上述程式碼會將儲存格A3的值更新為New Value of A3 。
我們也可以使用 range 函數將多個儲存格的值更新為靜態值:
ws["A3:C3"].Value = "New Value";ws["A3:C3"].Value = "New Value";ws("A3:C3").Value = "New Value"這將使用New Value更新 Excel 檔案中第 3 行A3到C3儲存格的內容。
透過這些範例了解更多關於在 C# 中使用 Range 函數的資訊。
替換單元格值
IronXL 的優點之一在於它能夠輕鬆地將現有 Excel 檔案中的old values替換為new values ,涵蓋以下所有方面:
- 取代整個工作表中的值:
ws.Replace("old value", "new value");ws.Replace("old value", "new value");ws.Replace("old value", "new value")- 替換特定行的值:
ws.Rows[RowIndex].Replace("old value", "new value");ws.Rows[RowIndex].Replace("old value", "new value");ws.Rows(RowIndex).Replace("old value", "new value")- 替換特定列的值:
ws.Columns[ColumnIndex].Replace("old value", "new Value");ws.Columns[ColumnIndex].Replace("old value", "new Value");ws.Columns(ColumnIndex).Replace("old value", "new Value")- 替換特定範圍內的值:
ws["From:To"].Replace("old value", "new value");ws["From:To"].Replace("old value", "new value");ws("From:To").Replace("old value", "new value")讓我們來看一個例子,以便清楚地了解如何在我們的 C# 項目中使用上述函數來替換值。 在這個例子中,我們將使用 replace 函數來取代特定範圍內的值。
// Import the IronXL library
using IronXL;
static void Main(string[] args)
{
// Access the WorkBook and WorkSheet
WorkBook wb = WorkBook.Load("sample.xlsx");
WorkSheet ws = wb.GetWorkSheet("Sheet1");
// Specify a range from B5 to G5 and replace "Normal" value with "Good"
ws["B5:G5"].Replace("Normal", "Good");
// Save the updated Excel file
wb.SaveAs("sample.xlsx");
}// Import the IronXL library
using IronXL;
static void Main(string[] args)
{
// Access the WorkBook and WorkSheet
WorkBook wb = WorkBook.Load("sample.xlsx");
WorkSheet ws = wb.GetWorkSheet("Sheet1");
// Specify a range from B5 to G5 and replace "Normal" value with "Good"
ws["B5:G5"].Replace("Normal", "Good");
// Save the updated Excel file
wb.SaveAs("sample.xlsx");
}' Import the IronXL library
Imports IronXL
Shared Sub Main(ByVal args() As String)
' Access the WorkBook and WorkSheet
Dim wb As WorkBook = WorkBook.Load("sample.xlsx")
Dim ws As WorkSheet = wb.GetWorkSheet("Sheet1")
' Specify a range from B5 to G5 and replace "Normal" value with "Good"
ws("B5:G5").Replace("Normal", "Good")
' Save the updated Excel file
wb.SaveAs("sample.xlsx")
End Sub上述程式碼會將B5到G5中的Normal值替換為Good ,工作表的其餘部分保持不變。 了解更多關於如何使用 IronXL 的此功能編輯 Excel 區域中儲存格值的資訊。
刪除 Excel 檔案中的行
在應用程式開發中,我們有時需要透過程式設計方式刪除現有 Excel 檔案中的整行資料。 為此,我們使用 IronXL 的Remove()函數。 以下是一個範例:
// Import the IronXL library
using IronXL;
static void Main(string[] args)
{
// Access the WorkBook and WorkSheet
WorkBook wb = WorkBook.Load("sample.xlsx");
WorkSheet ws = wb.GetWorkSheet("Sheet1");
// Remove the row number 2
ws.Rows[2].Remove();
// Save the updated Excel file
wb.SaveAs("sample.xlsx");
}// Import the IronXL library
using IronXL;
static void Main(string[] args)
{
// Access the WorkBook and WorkSheet
WorkBook wb = WorkBook.Load("sample.xlsx");
WorkSheet ws = wb.GetWorkSheet("Sheet1");
// Remove the row number 2
ws.Rows[2].Remove();
// Save the updated Excel file
wb.SaveAs("sample.xlsx");
}' Import the IronXL library
Imports IronXL
Shared Sub Main(ByVal args() As String)
' Access the WorkBook and WorkSheet
Dim wb As WorkBook = WorkBook.Load("sample.xlsx")
Dim ws As WorkSheet = wb.GetWorkSheet("Sheet1")
' Remove the row number 2
ws.Rows(2).Remove()
' Save the updated Excel file
wb.SaveAs("sample.xlsx")
End Sub上述程式碼將刪除sample.xlsx的第2行。
教程快速存取
常見問題解答
不使用 Interop,如何在 C# 中讀取 Excel 檔案?
您可以使用 IronXL 在 C# 中讀取 Excel 檔案,而不需要 Interop。使用 WorkBook.Load() 函式載入檔案,並使用 WorkBook.GetWorkSheet() 存取工作表。
C# 程式化建立新 Excel 檔案的流程為何?
透過 IronXL,您可以使用 WorkBook.Create() 方法建立新的 Excel 檔案,然後再使用 WorkSheet.CreateWorkSheet() 將資料加入其中。
是否可以在不使用 Interop 的情況下用 C# 修改 Excel 檔案?
是的,IronXL.Excel 提供了在不使用 Interop 的情況下修改 Excel 檔案的功能,包括更新儲存格值、取代舊值,以及直接移除行或列。
如何使用 IronXL.Excel 更新 Excel 表單中特定的儲存格值?
若要更新儲存格值,請使用 WorkBook.GetWorkSheet() 載入工作表,為儲存格指定新值,然後儲存您的變更。
我可以使用 IronXL 替換單元格範圍中的值嗎?
IronXL 允許您在工作表或特定範圍物件上使用 Replace() 函式來取代範圍中的值。
與 Microsoft.Office.Interop.Excel 相比,使用 IronXL 有哪些優勢?
IronXL.Excel 透過提供易於使用的 API 簡化 Excel 檔案操作,減少對複雜 Interop 程式碼的需求,並提供更佳的效能與可靠性。
如何使用 IronXL.Excel 移除 Excel 檔案中的一行?
若要移除 IronXL 中的一行,請對工作表中指定的行物件使用 Remove() 函式。
IronXL.Excel 是否支援將 Excel 檔案轉換為 DataSets 和 DataTables?
是的,IronXL 支援將工作簿轉換為 DataSets,以及將工作表轉換為 DataTables,讓資料處理更加靈活。
如何在 C# 專案中安裝 IronXL?
您可以從 Iron Software 網站下載 IronXL,或使用 NuGet 套件管理員的指令,在您的 C# 專案中安裝 IronXL:Install-Package IronXL.Excel.
IronXL 是否適合大型 Excel 檔案?
IronXL.Excel 經過最佳化,可有效率地處理大型 Excel 檔案,與傳統的 Interop 方法相比,處理速度快且記憶體使用量最小。








