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

时间:2014-04-16 21:24:28

标签: c#

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

2 个答案:

答案 0 :(得分:0)

答案 1 :(得分:0)

在此链接中查看答案: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);
    }
}