使用 Microsoft Office Interop Excel C# 讀取 Excel 檔案:以及一種無需 Office 即可更快建立 Excel 檔案的方法
如果您曾經嘗試使用 Microsoft Office Interop Excel C# 讀取 Excel 文件,您一定知道其中的挫折感:版本不符、COM 物件洩漏,以及必須在執行程式碼的每台電腦上安裝 Microsoft Office 的硬性需求。 在本文中,我們將帶您了解傳統的互通方法,解釋它的不足之處,然後展示IronXL 如何讓您輕鬆建立、讀取和寫入 Excel 文件,而無需擔心這些問題。
!{--01001100010010010100001001010010010000010101001001011001010111110100011101000101010101 01000101111101010011010101000100000101010010010101000100010101000100010111110101011101001000110 1010101000100100001011111010100000101001001001111010001000101010101010000110101010100101010101011 10101010001010010010010010010000010100110001011111010000100100110001001111101000011010010111111010000110100101110--
Interop 庫如何建立 Excel 工作簿?
Microsoft.Office.Interop.Excel 命名空間公開了 Excel 內部使用的相同 COM 物件模型。 要透過此互通庫讀取或建立 Excel 文件,首先需要實例化一個 Application 對象,將新工作簿新增至其 Workbooks 集合中,然後存取各個工作表單元格。 以下範例示範了一個使用 Microsoft.Office.Interop.Excel 建立 XLSX 檔案並將值寫入儲存格的最小控制台應用程式。
using Excel = Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;
// Create the Excel Application COM object
Excel.Application excelApp = new Excel.Application();
if (excelApp == null)
{
Console.WriteLine("Error: Excel is not properly installed.");
return;
}
// Add a new workbook and access the default worksheet
Excel.Workbook xlWorkBook = excelApp.Workbooks.Add(Type.Missing);
Excel.Worksheet xlWorkSheet = (Excel.Worksheet)xlWorkBook.ActiveSheet;
// Write data into specific cells
xlWorkSheet.Cells[1, 1] = "Product";
xlWorkSheet.Cells[1, 2] = "Price";
xlWorkSheet.Cells[2, 1] = "Widget";
xlWorkSheet.Cells[2, 2] = "29.99";
// Save as an XLSX file and clean up COM objects
string filepath = @"C:\Reports\products.xlsx";
xlWorkBook.SaveAs(filepath);
xlWorkBook.Close(false);
excelApp.Quit();
// Release every COM object to prevent orphaned Excel processes
Marshal.ReleaseComObject(xlWorkSheet);
Marshal.ReleaseComObject(xlWorkBook);
Marshal.ReleaseComObject(excelApp);
using Excel = Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;
// Create the Excel Application COM object
Excel.Application excelApp = new Excel.Application();
if (excelApp == null)
{
Console.WriteLine("Error: Excel is not properly installed.");
return;
}
// Add a new workbook and access the default worksheet
Excel.Workbook xlWorkBook = excelApp.Workbooks.Add(Type.Missing);
Excel.Worksheet xlWorkSheet = (Excel.Worksheet)xlWorkBook.ActiveSheet;
// Write data into specific cells
xlWorkSheet.Cells[1, 1] = "Product";
xlWorkSheet.Cells[1, 2] = "Price";
xlWorkSheet.Cells[2, 1] = "Widget";
xlWorkSheet.Cells[2, 2] = "29.99";
// Save as an XLSX file and clean up COM objects
string filepath = @"C:\Reports\products.xlsx";
xlWorkBook.SaveAs(filepath);
xlWorkBook.Close(false);
excelApp.Quit();
// Release every COM object to prevent orphaned Excel processes
Marshal.ReleaseComObject(xlWorkSheet);
Marshal.ReleaseComObject(xlWorkBook);
Marshal.ReleaseComObject(excelApp);
Imports Excel = Microsoft.Office.Interop.Excel
Imports System.Runtime.InteropServices
' Create the Excel Application COM object
Dim excelApp As Excel.Application = New Excel.Application()
If excelApp Is Nothing Then
Console.WriteLine("Error: Excel is not properly installed.")
Return
End If
' Add a new workbook and access the default worksheet
Dim xlWorkBook As Excel.Workbook = excelApp.Workbooks.Add(Type.Missing)
Dim xlWorkSheet As Excel.Worksheet = CType(xlWorkBook.ActiveSheet, Excel.Worksheet)
' Write data into specific cells
xlWorkSheet.Cells(1, 1) = "Product"
xlWorkSheet.Cells(1, 2) = "Price"
xlWorkSheet.Cells(2, 1) = "Widget"
xlWorkSheet.Cells(2, 2) = "29.99"
' Save as an XLSX file and clean up COM objects
Dim filepath As String = "C:\Reports\products.xlsx"
xlWorkBook.SaveAs(filepath)
xlWorkBook.Close(False)
excelApp.Quit()
' Release every COM object to prevent orphaned Excel processes
Marshal.ReleaseComObject(xlWorkSheet)
Marshal.ReleaseComObject(xlWorkBook)
Marshal.ReleaseComObject(excelApp)
上述程式碼建立一個 Excel 工作簿,以行和儲存格值填入工作表,儲存文件,然後手動釋放每個 COM 物件。 最後那個清理步驟不是可選項——跳過它,你會發現系統上存在佔用記憶體的幽靈 EXCEL.EXE 進程。 也要注意,程式碼會檢查 Application 物件是否為空; 如果未安裝 Microsoft Office,則之後的每一行都會報錯。 Office 互通函式庫的版本必須與電腦上的 Office 版本相符,否則您將遇到 FileNotFoundException 和類似的執行時間錯誤,這些錯誤出了名的難以偵錯。
Visual Basic 開發人員在使用 Excel Microsoft.Office.Interop.Excel 時會遇到相同的挑戰,因為 .NET 語言的底層 COM 基礎架構是相同的。
互通方法在伺服器和雲端會造成哪些問題?
微軟明確不建議在伺服器環境中使用 Office Interop。 互通性庫會在背景啟動一個完整的 Excel 應用程式實例,這表示每個對 Web 伺服器或雲端應用程式的請求都會啟動一個隱藏的 Windows 桌面進程。 在Linux伺服器上,它完全無法運作。 當未安裝 Office 或不同版本的 Microsoft Office 相互衝突時,資料庫連接字串、檔案系統路徑和使用者權限都會成為額外的故障點。
開發者經常在Stack Overflow和Microsoft Q&A上發布關於這些問題的帖子,尋找在不安裝 Excel 的情況下讀取 Excel 檔案和建立 Excel 檔案的方法。 下表總結了主要差異。
|特點| Office Interop |IronXL| |---|---|---| | 需要安裝 Excel | 是的——只有開發人員的機器和所有生產伺服器。 |無| | 支援的 Excel 文件格式 | XLS、XLSX | XLS、XLSX、CSV、TSV、JSON、XML | | 跨平台(.NET Core、Linux、macOS) |僅限 Windows| Windows、Linux、macOS、Azure | | 需要清理 COM 對象 | 是的-手動 Marshal.ReleaseComObject |無| | 伺服器/雲端部署 | 微軟不推薦 |完全支援| | 表現 | 速度較慢-啟動隱藏的 Excel 進程 | 更佳效能-託管的 .NET 程式碼 | | .NET Framework 和 .NET Core 支持 | 僅限 .NET Framework | .NET Framework、.NET Core、.NET 5-10 |
如何在未安裝 Microsoft Office 的情況下建立 Excel 檔案?
IronXL 是一個.NET Excel 函式庫,它完全使用託管程式碼讀取、寫入和建立 Excel 檔案。 它不依賴 Microsoft Office,無需發布 COM 對象,也無需調試版本衝突。 在 Visual Studio 中使用解決方案資源管理器透過 NuGet 安裝 IronXl.Excel,即可開始使用。 它在所有主流作業系統上的 .NET Framework 4.6.2+、.NET Core 以及 .NET 5 到 .NET 10 都能正常運作。
using IronXL;
// Create a new Excel workbook — default value is XLSX format
WorkBook workBook = WorkBook.Create(ExcelFileFormat.XLSX);
// Add a worksheet and populate cells with data
WorkSheet workSheet = workBook.CreateWorkSheet("Sales");
workSheet["A1"].Value = "Product";
workSheet["B1"].Value = "Price";
workSheet["A2"].Value = "Widget";
workSheet["B2"].Value = 29.99;
// Apply basic formatting
workSheet["A1"].Style.Font.Bold = true;
workSheet["B1"].Style.Font.Bold = true;
// Save the XLSX file
workBook.SaveAs(@"C:\Reports\products.xlsx");
using IronXL;
// Create a new Excel workbook — default value is XLSX format
WorkBook workBook = WorkBook.Create(ExcelFileFormat.XLSX);
// Add a worksheet and populate cells with data
WorkSheet workSheet = workBook.CreateWorkSheet("Sales");
workSheet["A1"].Value = "Product";
workSheet["B1"].Value = "Price";
workSheet["A2"].Value = "Widget";
workSheet["B2"].Value = 29.99;
// Apply basic formatting
workSheet["A1"].Style.Font.Bold = true;
workSheet["B1"].Style.Font.Bold = true;
// Save the XLSX file
workBook.SaveAs(@"C:\Reports\products.xlsx");
Imports IronXL
' Create a new Excel workbook — default value is XLSX format
Dim workBook As WorkBook = WorkBook.Create(ExcelFileFormat.XLSX)
' Add a worksheet and populate cells with data
Dim workSheet As WorkSheet = workBook.CreateWorkSheet("Sales")
workSheet("A1").Value = "Product"
workSheet("B1").Value = "Price"
workSheet("A2").Value = "Widget"
workSheet("B2").Value = 29.99
' Apply basic formatting
workSheet("A1").Style.Font.Bold = True
workSheet("B1").Style.Font.Bold = True
' Save the XLSX file
workBook.SaveAs("C:\Reports\products.xlsx")
使用IronXL建立的 Excel 文件
使用 Microsoft Office Interop Excel C# 讀取 Excel 文件:以及無需 Office 即可更快建立 Excel 文件的方法:圖 1 -IronXL輸出文件
上述程式碼實現了與 Interop 範例相同的結果,但程式碼行數減少了一半,並且沒有外部相依性。 WorkBook.Create() 初始化一個指定Excel 檔案格式(預設為 XLSX)的新工作簿,而 CreateWorkSheet 新增一個命名的工作表。 單元格值透過簡潔的索引器語法設置,SaveAs 會自動處理檔案副檔名。 沒有 Quit(),沒有 Marshal.ReleaseComObject,沒有隱藏進程。 同一個 API 也支援透過一次方法呼叫儲存為 XLS、CSV、JSON 或 XML 格式,有關所有可用選項,請參閱匯出文件。
IronXL 還可以與 System.Data 物件無縫集成,因此從資料庫連接字串流經 DataTable 的資料可以直接寫入工作表,而無需手動逐行迭代。
如何跨行和單元格讀取和寫入工作表資料?
讀取現有的Excel檔案同樣簡單。 WorkBook.Load 方法接受一個字串類型的檔案路徑,指向任何 XLS、XLSX 或 CSV 檔案。載入完成後,每個工作表都會將其行和儲存格作為可迭代集合公開,從而可以輕鬆讀取資料、修改值或將結果上傳到資料庫或伺服器端點。
using IronXL;
// Load an existing Excel file
WorkBook workBook = WorkBook.Load(@"C:\Reports\products.xlsx");
WorkSheet workSheet = workBook.DefaultWorkSheet;
// Read and display each row of data
foreach (var row in workSheet.Rows)
{
foreach (var cell in row.ToArray())
{
Console.Write(cell.Value + "\t");
}
Console.WriteLine();
}
// Update a specific cell and save
workSheet["B2"].Value = 34.99;
workBook.SaveAs(@"C:\Reports\products_updated.xlsx");
using IronXL;
// Load an existing Excel file
WorkBook workBook = WorkBook.Load(@"C:\Reports\products.xlsx");
WorkSheet workSheet = workBook.DefaultWorkSheet;
// Read and display each row of data
foreach (var row in workSheet.Rows)
{
foreach (var cell in row.ToArray())
{
Console.Write(cell.Value + "\t");
}
Console.WriteLine();
}
// Update a specific cell and save
workSheet["B2"].Value = 34.99;
workBook.SaveAs(@"C:\Reports\products_updated.xlsx");
Imports IronXL
' Load an existing Excel file
Dim workBook As WorkBook = WorkBook.Load("C:\Reports\products.xlsx")
Dim workSheet As WorkSheet = workBook.DefaultWorkSheet
' Read and display each row of data
For Each row In workSheet.Rows
For Each cell In row.ToArray()
Console.Write(cell.Value & vbTab)
Next
Console.WriteLine()
Next
' Update a specific cell and save
workSheet("B2").Value = 34.99
workBook.SaveAs("C:\Reports\products_updated.xlsx")
使用IronXL讀取 Excel 文件
本範例展示如何透過遍歷 Rows 集合並存取每個單元格的 Value 屬性來讀取 Excel 檔案。 嵌套循環模式——先使用 var row,再使用 var cell——反映了你自然而然地思考電子表格的方式。 讀取資料後,程式碼會更新單一儲存格並將工作簿儲存到新的 XLSX 檔案中,同時保留原始檔案。IronXL會在工作表被修改時自動重新計算所有 Excel 公式,互通性庫也提供了此功能,但代價是需要啟動一個完整的 Excel 實例。
對於公式、條件格式、合併儲存格或處理多個工作表等更進階的場景, IronXL API 參考涵蓋了所有可用的方法和屬性。 該程式庫還支援從 ASP.NET 控制器訪問,因此可以輕鬆地從 Web 應用程式或 API 端點生成和下載 Excel 文件,而無需在伺服器上安裝 Office。
.NET Excel自動化發展的最佳路徑是什麼?
如果一個專案被鎖定在已安裝 Microsoft Office 且版本穩定的舊版 Windows 桌面環境中,那麼互通程式庫可以很好地完成基本任務。 但對於其他所有情況,例如伺服器部署、雲端應用程式、跨平台構建,或任何需要更高效能和更少運行時錯誤的場景,獨立的 .NET Excel 庫顯然是最佳選擇。
IronXL 透過簡潔現代的 API 處理所有常見的 Excel 操作(建立工作簿、讀取Excel 試算表資料、寫入儲存格、儲存為多種檔案副檔名類型,包括 XLS 和 XLSX),該 API 可在任何 .NET 運作的地方運作。 它同時支援 C# 和 Visual Basic 項目,相同的程式碼無需修改即可在 Windows、Linux 和 macOS 上運行。
您可以開始 30 天免費試用,在自己的專案中進行測試,或在準備部署時探索授權選項。
常見問題解答
在 C# 中使用 Microsoft Office Interop Excel 有哪些限制?
在 C# 中使用 Microsoft Office Interop Excel 可能會導致版本不符、COM 物件洩漏等問題,並且需要在執行程式碼的每台電腦上安裝 Microsoft Office。
IronXL 如何改善 C# 中處理 Excel 檔案的流程?
IronXL 可讓您建立、讀取和寫入 Excel 文件,而無需 Microsoft Office,從而消除了版本不匹配和 COM 物件洩漏等問題。
IronXL 能否在未安裝 Microsoft Office 的伺服器上使用?
是的,IronXL 對伺服器安全,並且不需要安裝 Microsoft Office,因此它是一個用於處理 Excel 檔案的跨平台解決方案。
使用 IronXL 代替 Excel Interop 有哪些優勢?
IronXL 提供了一種更可靠、更有效率的方式來處理 Excel 文件,因為它不依賴 Microsoft Office,從而降低了版本不匹配和 COM 物件洩漏等常見問題的風險。
IronXL 是否相容於所有版本的 Excel 檔案?
IronXL 支援多種 Excel 檔案格式,包括 XLSX、XLS、CSV 和 TSV,使其能夠靈活地處理各種 Excel 檔案操作。
IronXL 在機器上運行是否需要任何特殊設定?
IronXL 不需要安裝 Microsoft Office,無需特殊設定即可輕鬆整合到您的 C# 專案中。
IronXL 能有效處理大型 Excel 文件嗎?
是的,IronXL 的設計初衷就是為了有效率地讀取和寫入大型 Excel 文件,提供快速的效能,而不受 Interop 的限制。
IronXL 支援哪些平台?
IronXL 是跨平台的,支援 Windows、Linux 和 MacOS,這使得它成為在不同環境下處理 Excel 檔案的靈活選擇。
IronXL 如何處理 Excel 檔案建立?
IronXL 提供了一個簡單的 API,可以使用 C# 以程式設計方式建立 Excel 文件,並提供格式化儲存格、管理工作表等功能。
IronXL用戶是否有社群或支援?
是的,IronXL 用戶可以存取文件、教程和社群支持,以幫助解決任何整合或使用問題。

