我在C#4.5中有以下代码。它只是使用Office 2013将简单的Hello world
写入word文档。
_Application word = new Application();
word.Visible = false;
_Document document = word.Documents.Add();
var file = Path.Combine(Directory.GetCurrentDirectory(), "test.docx");
try
{
document.Words.First.InsertBefore("Hello World");
document.SaveAs(file);
}
catch (Exception e)
{
logger.Fatal(e);
}
finally
{
if (document != null)
{
document.Close();
Marshal.FinalReleaseComObject(document);
}
application.Quit();
Marshal.FinalReleaseComObject(application);
}
在Windows 7和Windows Server 2012 R2下运行没有任何问题。但是当我在Teamcity下启动它时,在同一个Windows Server 2012 R2上,我预计会出现以下错误:
System.Runtime.InteropServices.COMException (0x800A1066): Command failed
at Microsoft.Office.Interop.Word.DocumentClass.SaveAs(Object& FileName, Object& FileFormat, Object& LockComments, Object& Password, Object& AddToRecentFiles, Object& WritePassword, Object& ReadOnlyRecommended, Object& EmbedTrueTypeFonts, Object& SaveNativePictureFormat, Object& SaveFormsData, Object& SaveAsAOCELetter, Object& Encoding, Object& InsertLineBreaks, Object& AllowSubstitutions, Object& LineEnding, Object& AddBiDiMarks)
at Interop.HelloWorld.HelloWord.<>c__DisplayClass4.<WriteIt>b__3() in c:\TeamCity\buildAgent\work\27b855ae6e536c44\Interop\HelloWorld\HelloWord.cs:line 58
at Interop.HelloWorld.HelloWord.WithDocument(_Application application, _Document document, Action handler) in c:\TeamCity\buildAgent\work\27b855ae6e536c44\Interop\HelloWorld\HelloWord.cs:line 72
System.Runtime.InteropServices.COMException (0x800A1066): Command failed
at Microsoft.Office.Interop.Word.DocumentClass.Close(Object& SaveChanges, Object& OriginalFormat, Object& RouteDocument)
at Interop.HelloWorld.HelloWord.WithDocument(_Application application, _Document document, Action handler) in c:\TeamCity\buildAgent\work\27b855ae6e536c44\Interop\HelloWorld\HelloWord.cs:line 92
at Interop.HelloWorld.HelloWord.WriteIt(String file) in c:\TeamCity\buildAgent\work\27b855ae6e536c44\Interop\HelloWorld\HelloWord.cs:line 52
at Interop.Program.Main(String[] args) in c:\TeamCity\buildAgent\work\27b855ae6e536c44\Interop\Program.cs:line 25
答案 0 :(得分:2)
解决这个问题:
Desktop
或C:\Windows\SysWOW64\config\systemprofile
下创建C:\Windows\System32\config\systemprofile
文件夹(取决于您的操作系统)dcomcnfg.exe
检查办公室组件的配置,并将属性更改为属性The interactive user
。 当心组件名称不同......
Document Microsoft Word 97-2003
Microsoft Excel Application
您可以在regedit
上使用HKCR\AppId
检索已注册的组件。所有Office 2013组件均按0000-0000-C000-000000000046