我創建一個Windows服務,將創建Excel表,我用Microsoft.Office.Interop.Excel但得到這個異常 Exception from HRESULT: 0x80080005 (CO_E_SERVER_EXEC_FAILURE
我已附加一個照片這裏Microsoft.Office.Interop.Excel錯誤與Windows服務
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();
Office程序「對VBA項目對象模型的信任訪問」是與服務會議高度不相容和Microsoft *強烈*不鼓勵這種做法。錯誤代碼只是告訴你它在啓動時崩潰,它不會告訴你它爲什麼崩潰。對此有許多可能的原因,沒有你可以看到。這就是爲什麼微軟不鼓勵它:) –
完全匹配,但它確實在Windows應用程序上使用按鈕點擊操作什麼會阻止它在Windows服務 – Skimo
然後它在用戶的會話中運行,Office程序當然被設計爲支持,因爲這就是他們他們總是跑的方式。服務會話最大的掛斷是一個非常小的桌面堆(因爲服務不需要創建用戶界面),它們運行的用戶帳戶出現問題,在以後的Office版本中檢測到它們在會話0中運行時出現無法識別的打印故障和對策並拒絕啓動。 –