Windows服务的Microsoft.Office.Interop.Excel错误

时间:2016-09-11 08:57:03

标签: c# windows-services interop excel-interop

我正在创建一个可以创建Excel工作表的Windows服务,我已经使用过Microsoft.Office.Interop.Excel但是遇到了这个异常         Exception from HRESULT: 0x80080005 (CO_E_SERVER_EXEC_FAILURE 我在这附上了一张照片

Exception photo attached

public void insertIntoSheet(string Name, DataTable dt)
{
    Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();

    if (xlApp == null)
    {
        //MessageBox.Show("Excel is not properly installed!!");
        return;
    }
    Excel.Workbook xlWorkBook;
    Excel.Worksheet xlWorkSheet;
    object misValue = System.Reflection.Missing.Value;

    xlWorkBook = xlApp.Workbooks.Add(misValue);
    xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
    for (int i = 1, j = 0; j < dt.Rows.Count; i++, j++)
    {
        xlWorkSheet.Cells[i, 1] = dt.Rows[j][0].ToString();
        xlWorkSheet.Cells[i, 2] = dt.Rows[j][1].ToString();
        xlWorkSheet.Cells[i, 3] = dt.Rows[j][2].ToString();
        xlWorkSheet.Cells[i, 4] = dt.Rows[j][3].ToString();
        xlWorkSheet.Cells[i, 5] = dt.Rows[j][4].ToString();
        xlWorkSheet.Cells[i, 6] = dt.Rows[j][5].ToString();
    }
    //xlWorkSheet.Cells[1, 1] = "Sheet 1 content";

    xlWorkBook.SaveAs(String.Format("d:\\{0}.xls", Name), Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
    xlWorkBook.Close(true, misValue, misValue);
    xlApp.Quit();

    releaseObject(xlWorkSheet);
    releaseObject(xlWorkBook);
    releaseObject(xlApp);
    Class_Library.WriteErrorLog("Inserting the sheet method finished");
    //MessageBox.Show("Excel file created , you can find the file d:\\csharp-Excel.xls");
}

private void releaseObject(object obj)
{
    try
    {
        System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
        obj = null;
    }
    catch (Exception ex)
    {
        obj = null;
        Class_Library.WriteErrorLog(ex.Message);
        //MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
    }
    finally
    {
        GC.Collect();
    }
}

注意:我在Windows应用程序中使用了与测试相同的代码,并且按预期工作。 我尝试过编写Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();并尝试仅使用名称Excel Excel.Application xlApp = new Excel.Application();

2 个答案:

答案 0 :(得分:0)

尝试编辑DCOMConfig

1.在DCOMCNFG中,右键单击“我的电脑”,然后选择属性。

2.转到Component / MyComputer / DCOMConfig

3.转到Microsoft Excel应用程序属性安全性

4.在启动和激活权限中,单击&#34; Custamize&#34;并添加网络 为它服务并给予它&#34;本地推出&#34;和&#34;本地激活&#34;允许。给出相同的访问权限和配置权限按OK就可以了。您现在可以运行我的应用程序。

答案 1 :(得分:0)

转到Excel的选项/信任中心/宏设置,然后选中“信任对VBA项目对象模型的访问权限”