【问题标题】:SaveAs MS-Word as docx instead of doc c#SaveAs MS-Word 为 docx 而不是 doc c#
【发布时间】:2014-04-16 21:24:27
【问题描述】:

当我尝试在 winform C# 中保存带有 docx 扩展名的文件并打开该文件时出现异常:
"word无法打开文件,因为文件格式与文件扩展名不匹配"

这是我保存文件的方式:

object oMissing = Missing.Value;
Word.Application oWord = new Word.Application();
Word.Document oWordDoc = new Word.Document();
oWord.Visible = false;
oWordDoc = oWord.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);  

Object oSaveAsFile = (Object)@"C:\test\FINISHED_XML_Template.docx";            
        oWordDoc.SaveAs(ref oSaveAsFile, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing);

        oWordDoc.Close(false, ref oMissing, ref oMissing);
        oWord.Quit(ref oMissing, ref oMissing, ref oMissing);

【问题讨论】:

  • 您使用的 Office COM 互操作库版本是否实际支持 docx 文件?
  • 我想是的,我使用的是 Microsoft Office 12.0 对象库
  • 在SaveAs 方法中你可以尝试将Word.WdSaveFormat.wdFormatXMLDocument 指定为第二个参数值吗?

标签: c#


【解决方案1】:

【讨论】:

    【解决方案2】:

    在此链接中查看答案:Convert .doc to .docx using C#

    Daves 解决方案如下所示,但我已将 Daves 代码从 CompatibilityMode:=WdCompatibilityMode.wdWord2010 到 CompatibilityMode:=WdCompatibilityMode.wdWord2013 更新并为您提供真正的 docx(无兼容模式)。

    public void ConvertDocToDocx(string path)
    {
        Application word = new Application();
    
        if (path.ToLower().EndsWith(".doc"))
        {
            var sourceFile = new FileInfo(path);
            var document = word.Documents.Open(sourceFile.FullName);
    
            string newFileName = sourceFile.FullName.Replace(".doc", ".docx");
            document.SaveAs2(newFileName,WdSaveFormat.wdFormatXMLDocument, 
                             CompatibilityMode: WdCompatibilityMode.wdWord2013);
    
            word.ActiveDocument.Close();
            word.Quit();
    
            File.Delete(path);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多