簡體   English   中英

另存為MS-Word作為docx而不是doc c#

[英]SaveAs MS-Word as docx instead of doc 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);

請參閱此鏈接中的答案: 使用C#將.doc轉換為.docx

Daves解決方案如下所示,但我已從CompatibilityMode:= WdCompatibilityMode更改了Daves代碼。 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);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM