【问题标题】:Convert .doc to .docx in c# / vb.net在 c# / vb.net 中将 .doc 转换为 .docx
【发布时间】:2016-01-25 21:29:45
【问题描述】:
Microsoft.Office.Interop.Word._Document mDocument = new Microsoft.Office.Interop.Word.Document();

*//This function will convert .doc to .docx
    Public Function FileSave(ByVal fileName As String, ByVal openPWD As String, ByVal savePWD As String)    
                mDocument.SaveAs2(fileName, WdSaveFormat.wdFormatXMLDocument, , openPWD, , savePWD)             
                End Function*

上面的函数已经编写了使用 word interop 将 .doc 文件转换为 .docx。 文件创建成功,但打开时文件内容丢失。

缺少某些东西,或者是否有任何替代方法可以在 c# 或 Vb.net 中将 .doc 转换为 .docx

【问题讨论】:

  • Microsoft.Office.Interop.Word._Document mDocument = new Microsoft.Office.Interop.Word.Document(); 这一行创建了一个新文档,因为它是新创建的,所以它是空的。您需要打开自己的文件。

标签: c# ms-word office-interop vb.net-2010


【解决方案1】:

您似乎正在内存中创建一个全新的 Word 文档,然后将其保存为 .DOCX,这就是输出文件为空的原因。

// This line just creates a brand new empty document
Microsoft.Office.Interop.Word._Document mDocument = new Microsoft.Office.Interop.Word.Document();

您需要先打开现有文档,然后再另存为您想要的文件类型。

类似这样的东西(我自己没有测试过,因为它没有在带有互操作的机器上)

Microsoft.Office.Interop.Word._Document mDocument = wordApp.Documents.Open(sourcepath);
mDocument.SaveAs(outputpath, WdSaveFormat.wdFormatXMLDocument);

应 OP 要求,如何获取 Word 实例

// Create Word object
Word._Application wordApp = null;

// Try and get an existing instance
try
{
    wordApp = (Word._Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Word.Application");
}
catch { /* Ignore error */ }

// Check if we got an instance, if not then create one
if (wordApp == null)
{
    wordApp = new Microsoft.Office.Interop.Word.Application();
}

//Now you can use wordApp
... wordApp.Documents.Open(...);

【讨论】:

  • wordApp 定义的对象在哪里
  • 对不起,假设你有一个。我已经添加了获取 Word 实例的代码。
  • @NKD 实际上,在 Word 应用程序中创建新文档的正确命令是:wordApp.Documents.ADD()。 Word 不以 .NET 开发人员所期望的方式支持 NEW 关键字,并且只应将其用于 Word.Application。对于在应用程序中运行的所有对象,使用 ADD 方法。
猜你喜欢
  • 2012-05-17
  • 1970-01-01
  • 2011-06-16
  • 1970-01-01
  • 1970-01-01
  • 2016-03-10
  • 2016-06-22
  • 1970-01-01
  • 2020-08-27
相关资源
最近更新 更多