【发布时间】:2022-01-04 21:46:45
【问题描述】:
我正在以递归方式从 Word 文档生成 XPS 文档,但出现以下错误
错误:
此命令不可用,因为没有打开文档。在第 65 行的 Miscrosoft.office.interop.Word.ApplicationClass.get_ActiveDocument
这是:
wordApp.ActiveDocument.SaveAs2(xpsFile, FileFormat: Word.WdSaveFormat.wdFormatXPS);
我正在使用以下代码将 Word 文件转换为 XPS 文件
public static string convertWordToXps(string path, string wordDocName)
{
Word.Application wordApp = new Word.Application();
wordApp.Documents.Open(string.Concat(path, "\\", wordDocName), ConfirmConversions: false, ReadOnly: false);
string xpsFile = string.Concat(path, "\\", Path.GetFileNameWithoutExtension(wordDocName), ".xps");
try
{
//wordApp.ActiveDocument.ExportAsFixedFormat(xpsFileName, WdExportFormat.wdExportFormatXPS, false, WdExportOptimizeFor.wdExportOptimizeForOnScreen, WdExportRange.wdExportAllDocument, 1, 1, WdExportItem.wdExportDocumentContent, false, true, WdExportCreateBookmarks.wdExportCreateNoBookmarks, false, true, false, nullObject);
wordApp.ActiveDocument.SaveAs2(xpsFile, FileFormat: Word.WdSaveFormat.wdFormatXPS);
return xpsFile;
}
catch (Exception e)
{
MessageBox.Show(e.getDetailedErrorMessage());
}
finally
{
wordApp.Quit(SaveChanges: false, OriginalFormat: Type.Missing, RouteDocument: Type.Missing);
}
return null;
}
搜索功能
private void SearchDocuments(string directoryPath)
{
try
{
foreach (string fullName in Directory.GetFiles(directoryPath, "*.odt"))
{
InstructionsViewModel.convertWordToXps(System.IO.Path.GetDirectoryName(fullName), System.IO.Path.GetFileNameWithoutExtension(fullName));
}
foreach (string nestedDirectory in Directory.GetDirectories(directoryPath))
{
SearchDocuments(nestedDirectory);
}
}
catch (System.Exception error)
{
}
}
我想将所有文件夹中的所有word文件都转换为XPS
【问题讨论】:
-
旁注:使用Path.Combine Method 代替字符串连接。它负责删除多余的反斜杠或添加缺少的反斜杠。
-
@OlivierJacot-Descombes 感谢您的建议,但这不是这里的问题
-
@Muhammadzubair 在保存之前尝试激活您的文档:
wordApp.Documents(wordDocName"+".extension_of_doc").Activate()您只打开了文档,但它没有激活。 -
@BartoszOlchowik 你能发布你的解决方案吗?