C# Excel Interop Workaround
許多專案使用Excel來清楚地溝通,但如果您使用Microsoft.Office.Interop.Excel,那麼您很可能不得不面對許多複雜的程式碼行。 在本教程中,我們將使用IronXL作為C# Excel Interop替代方案,這樣您就不必使用Interop來完成您的專案。 您可以使用C#程式設計處理Excel檔案資料,建立Excel檔案,編輯和操控等。
C# Excel 無需Interop
- 下載Excel無需Interop程式庫
- 在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檔案small business。 其他值從B10相同,並在輸出中顯示。
資料集和資料表
我們還可以根據這些指引將Excel檔案作為資料集和資料表使用。
:path=/static-assets/excel/content-code-examples/get-started/c-sharp-excel-interop-3.cs
// 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);
Imports System.Data
' 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
上述程式碼將建立一個名為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的值。
我們還可以使用範圍功能用靜態值更新多個單元格:
ws["A3:C3"].Value = "New Value";
ws["A3:C3"].Value = "New Value";
ws("A3:C3").Value = "New Value"
這將用C3的單元格。
在這些例子中了解更多關於如何在C#中使用範圍函式。
替換單元格值
IronXL的一個強項是能輕鬆替換new values在現有Excel檔案中,涵蓋以下所有方面:
- 替換整個工作表的值:
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#專案中使用上述函式來替換值。 在此範例中,我們將使用替換功能來替換特定範圍內的值。
// 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
上述程式碼將從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
上述程式碼將移除2行。
快速存取教程
常見問題
如何在不使用 Interop 的情況下在 C# 中讀取 Excel 文件?
您可以使用 IronXL 來在 C# 中讀取 Excel 文件而不需 Interop。使用 WorkBook.Load() 函式載入文件,並使用 WorkBook.GetWorkSheet() 存取工作表。
在 C# 中程式化建立新的 Excel 文件的過程是什麼?
using IronXL,您可以通過使用 WorkBook.Create() 方法來建立新的 Excel 文件,然後使用 WorkSheet.CreateWorkSheet() 新增資料。
是否可以在不使用 Interop 的情況下在 C# 中修改 Excel 文件?
是的,IronXL 提供了在不需要 Interop 的情況下修改 Excel 文件的能力,可以直接更新單元格值、替換舊值和刪除行或列。
如何使用 IronXL 更新 Excel 表格中的特定單元格值?
要更新單元格值,請使用 WorkBook.GetWorkSheet() 載入工作表,將新值賦給單元格,然後保存更改。
我可以使用 IronXL 替換一範圍內的單元格值嗎?
IronXL 允許您使用工作表或特定範圍物件上的 Replace() 函式替換一範圍內的值。
using IronXL 比 Microsoft.Office.Interop.Excel 有什麼優勢?
IronXL 提供了簡化 Excel 文件操作的易用 API,減少了對複雜 Interop 程式碼的需求,並提供了更好的性能和可靠性。
如何使用 IronXL 從 Excel 文件中刪除某一行?
要在 IronXL 中刪除一行,請使用指定工作表中行物件上的 Remove() 函式。
IronXL 是否支持將 Excel 文件轉換為 DataSet 和 DataTable?
是的,IronXL 支持將工作簿轉換為 DataSet,將工作表轉換為 DataTable,提供更靈活的資料操作。
如何在 C# 項目中安裝 IronXL?
您可以從 Iron Software 官網下載或使用 NuGet 套件管理器安裝 IronXL,命令為:Install-Package IronXL.Excel。
IronXL 適合大型 Excel 文件嗎?
IronXL 經過優化以有效處理大型 Excel 文件,提供快速的處理速度和較低的記憶體使用量,相較於傳統的 Interop 方法。



