Microsoft サポート ベースの記事で、オフィス製品の UI レスの自動化はサポートされていないと述べていることはよく知っています。Windows Server 2008 x64 および Excel 2007は、指定されたステートメントを強制しているようです。
NT サービス (ローカル システム アカウント) の OnStart メソッドで次のコードを実行しています。コンソール アプリケーションで同じコードを実行すると、Excel が自動化されるだけです。
提供されたコードには 2 つの部分があります。最初の部分では、Excel を起動し、新しいワーク ブックを作成して、指定されたファイル名に保存します。2 番目の部分は、Excel の新しいインスタンスを起動し、指定されたファイルを開きます。オープン操作は、次の例外で終了します。
サービスを開始できません。System.Runtime.InteropServices.COMException (0x800A03EC): Microsoft Office Excel はファイル 'c:\temp\test.xls' にアクセスできません。いくつかの理由が考えられます。
• ファイル名またはパスが存在しません。? ファイルが別のプログラムによって使用されています。? 保存しようとしているブックは、現在開いているブックと同じ名前です。
自動化された Excel を起動してファイルをディスクに書き込むことができたのに、既存のファイルを開くように "ただ" 要求されたときに失敗したのはなぜですか?
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
// launch excel and create/save a new work book
Microsoft.Office.Interop.Excel.ApplicationClass excel = new Microsoft.Office.Interop.Excel.ApplicationClass();
excel.UserLibraryPath, excel.Interactive));
//
string filename = "c:\\temp\\test.xls";
if(System.IO.File.Exists(filename)) System.IO.File.Delete(filename);
//
excel.Workbooks.Add(System.Reflection.Missing.Value);
excel.Save(filename);
excel.Quit();
excel = null;
// lauch new instance of excel and open saved file
excel = new Microsoft.Office.Interop.Excel.ApplicationClass();
try
{
Microsoft.Office.Interop.Excel.Workbook book = excel.Workbooks.Open(filename,
System.Reflection.Missing.Value,
System.Reflection.Missing.Value,
System.Reflection.Missing.Value,
System.Reflection.Missing.Value,
System.Reflection.Missing.Value,
true,
System.Reflection.Missing.Value,
System.Reflection.Missing.Value,
false,
false,
System.Reflection.Missing.Value,
false,
System.Reflection.Missing.Value,
System.Reflection.Missing.Value);
book.Close(false, System.Reflection.Missing.Value, System.Reflection.Missing.Value);
book = null;
}
finally
{
excel.Quit();
excel = null;
}
//
GC.Collect();