如何从 Windows 服务运行 excel vba 代码

use*_*787 1 c# windows excel vba windows-services

我想从我的 Windows 服务运行一些 excel vba 代码。该服务正在使用 fileSystemWatcher 来监视要添加的 xml 文件的目录。添加文件后,xml 文件的内容将反序列化为对象属性。在这个阶段,我想打开一个 excel 文件并将这些值传递给某些单元格并运行该工作簿中的 vba 代码。我在 Windows 窗体应用程序中完美地运行了这个,但我无法从我的 Windows 服务应用程序中得到它。我将调试器附加到应用程序以尝试查看发生了什么,但没有抛出错误并且所有步骤都成功完成。我知道 Windows 服务不支持打开 MS Office 文件,因为与 UI 交互和它拥有的用户权限存在问题。但是我正在寻找一种能够从服务中运行此 vba 代码的方法。我使用的是 Windows 7 Home Premium 32 位,并且我的服务帐户设置为 LocalSystem。这是我使用的代码:

    private void FSWatcherTest_Created(object sender, System.IO.FileSystemEventArgs e)
    {
            Trade t;
            XmlSerializer serializer;
            XmlReader reader;
            XmlWriter writer;

            string filePath = @"C:\Inbox\TradeInfo.xml";


            serializer = new XmlSerializer(typeof(Trade));
            reader = XmlReader.Create(filePath);
            t = (Trade)serializer.Deserialize(reader);
            reader.Close();



            string path=@"C:\Windows\System32\config\systemprofile\Desktop\TwsDde.xls";

            oXL = new Microsoft.Office.Interop.Excel.Application();

            oXL.Visible = true;

            oXL.DisplayAlerts = false;

            mWorkBook = oXL.Workbooks.Open(path,2, false, 5, "", "", true,Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, true,false, false);

            //Get all the sheets in the workbook

            mWorkSheets = mWorkBook.Worksheets;

            //Get the allready exists sheet

            mWSheet1=(Microsoft.Office.Interop.Excel.Worksheet)mWorkSheets.get_Item("Basic Orders");

            // Microsoft.Office.Interop.Excel.Range range= mWSheet1.UsedRange;

            mWSheet1.Cells[12, 1] = "GE";
            mWSheet1.Cells[12, 2] = "STK";
            mWSheet1.Cells[12, 7] = "SMART";
            mWSheet1.Cells[12, 9] = "USD";
            mWSheet1.Cells[12, 12] = "Buy";
            mWSheet1.Cells[12, 13] = "100";
            mWSheet1.Cells[12, 14] = "MKT";

            Excel.Range range;
            Excel.Range row;

            range = mWSheet1.get_Range("A12", "O12");
            range.EntireRow.Select();

            oXL.Run("TwsDde.xls!Sheet2.placeOrder");
        }
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激。或者做同样事情的替代方法,即运行包含此代码的 Windows 窗体?

Dav*_*nan 5

不支持您尝试执行的操作:

Microsoft 当前不建议也不支持从任何无人参与的非交互式客户端应用程序或组件(包括 ASP、ASP.NET、DCOM 和 NT 服务)自动化 Microsoft Office 应用程序,因为 Office 可能表现出不稳定的行为和/或在此环境中运行 Office 时出现死锁。

如果该过程在交互式桌面中运行,您可以自动化 Excel。不支持从非交互式桌面(例如从会话)自动化 Excel 的尝试并且失败。