Hôm nay nhân có vụ liên quan đến đọc/ ghi file Excel phải dùng tới Microsoft.Office.Interop.Excel.dll trên ứng dụng web nên tui mới viết cái này để dành.
Sự tình là trên máy developer có cài đặt đầy đủ Visual Studio và Office, code ngon lành, chạy localhost ầm ầm. Vác lên server thì quẳng ra cái lỗi hết sức đau đớn
Retrieving the COM class factory for component with CLSID {00024500-0000-0000-C000-000000000046} failed due to the following error: 80040154 Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)).
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Runtime.InteropServices.COMException: Retrieving the COM class factory for component with CLSID {00024500-0000-0000-C000-000000000046} failed due to the following error: 80040154 Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)).
Hồi xưa cũng có gặp một lần rồi nhưng do làm biếng tìm hiểu quá nên tui nhảy qua xài OpenXML hoặc NPOI (một third-party component miễn phí có trên CodePlex) cho lẹ, giờ nhân tiện gặp nữa thì sẵn mò luôn cho biết.
Theo vốn tiếng Tây bằng cái lá mít của tui thì đại loại là cái dll đó chưa có đăng ký trong hệ thống. Thế là tui tìm cách đăng ký cái dll này bằng cách thông thường qua regsvr32, không được thì mò vô DCOM Config (dcomcnfg) cũng không được. Lên Google vái tứ phương thì thấy thằng Microsoft có cái cục Primary Interop Assemblies Redistributable (PIA) tui liền download về cài vô thử cũng không xi nhê miếng nào.
Tiếp tục search nữa – đúng là cái thời này không có Google chắc tui chết quá 😀 – thì thấy bác Johan trên weblogs.asp.net bảo rằng “Never, never, never do Office interop on the server” (link: http://weblogs.asp.net/jdanforth/archive/2011/05/15/never-never-never-do-office-interop-on-the-server.aspx), rồi thấy trong cái KB “Considerations for server-side Automation of Office” (link: http://support.microsoft.com/default.aspx?scid=kb;EN-US;q257757#kb2) của bác Microsoft cũng nói là
“Microsoft does not currently recommend, and does not support, Automation of Microsoft Office applications from any unattended, non-interactive client application or component (including ASP, ASP.NET, DCOM, and NT Services), because Office may exhibit unstable behavior and/or deadlock when Office is run in this environment.”
Tới nước này thì có một thằng ở trong tui kêu “bỏ đi, đừng cố gắng nữa, xài cách khác cho rồi” nên tui cũng xuôi xuôi theo và kết luận là ngoài cài bộ Office lên server thì hết đường binh rồi! 😀