将MS Word另存为docx,而不是doc c#

本文关键字:doc MS Word 另存为 docx | 更新日期: 2023-09-27 17:58:37

当我尝试在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);

将MS Word另存为docx,而不是doc c#

此页面建议更改为使用Word.Application.SaveAs2()方法。

http://social.msdn.microsoft.com/Forums/en-US/0d7a68c0-e2cd-41c0-9815-63f0fde0bc8d/converting-doc-to-docx?forum=worddev

请参阅此链接中的答案:使用C#将.doc转换为.docx

Daves的解决方案如下,但我已将Daves代码从CompatibilityMode:=WdCompatibilityModewdWord2010转换为CompatibilityMode:=WdCompatibilityModewdWord2013以便更新并为您提供真正的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);
    }
}