【问题标题】:Word Document SaveAs2 in Format wdFormatDocument97格式为 wdFormatDocument97 的 Word 文档 SaveAs2
【发布时间】:2016-11-25 07:03:51
【问题描述】:

我正在使用 Microsoft Interop Word 版本 15.0.0.0 来创建一个新的 Word 文档,在其中插入一些文本并保存它。

当我使用以下命令保存它时:

document.SaveAs2(wordFilePath);

文档以 DOCX 格式保存。

但是当我使用以下命令保存它时:

document.SaveAs2(wordFilePath, Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatDocument97);

该文档看似保存为 Word-97 DOC(Windows 资源管理器显示它带有 Word-97 DOC 图标和类型),但它实际上在内部保存为 DOCX(我可以通过两种方式看到这一点:它具有相同的大小对应的DOCX,当我用Word-2016打开它并选择另存为时,默认的保存格式是DOCX!)。

如何将文档保存为 real document-97 格式?

这是用于创建新 Word 文档的函数,其类型取决于给定文件路径的扩展名(DOC 与 DOCX):

public static void TextToMsWordDocument(string body, string wordFilePath)
{
    Microsoft.Office.Interop.Word.Application winword = new Microsoft.Office.Interop.Word.Application();
    winword.Visible = false;
    object missing = System.Reflection.Missing.Value;
    Microsoft.Office.Interop.Word.Document document = winword.Documents.Add(ref missing, ref missing, ref missing, ref missing);
    if (body != null)
    {
        document.Content.SetRange(0, 0);
        document.Content.Text = (body + System.Environment.NewLine);
    }
    if (System.IO.Path.GetExtension(wordFilePath).ToLower() == "doc")
        document.SaveAs2(wordFilePath, Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatDocument97);
    else // Assuming a "docx" extension:
        document.SaveAs2(wordFilePath);
    document.Close(ref missing, ref missing, ref missing);
    document = null;
    winword.Quit(ref missing, ref missing, ref missing);
    winword = null;
}

这是用于调用此函数的代码:

TextToMsWordDocument("abcdefghijklmnopqrstuvwxyz", "text.doc");
TextToMsWordDocument("abcdefghijklmnopqrstuvwxyz", "text.docx");

【问题讨论】:

  • 我尝试使用基于文档的加载项来复制它,但它没有显示出您提到的相同症状,并且 zip 结构与 docx 格式有很大不同。您可能需要发布一个最小的、完整的、可验证的示例。 stackoverflow.com/help/how-to-ask
  • 还有哪个版本的Word?我在 2010 年测试过。
  • @Chris:我使用的是 Word-2016 和 Interop.Word 版本 15.0.0.0。在我的问题中添加了这些详细信息和我的代码的简短版本。谢谢。
  • 我可以使用针对 14.0 和 15.0 的代码复制它。但我不确定为什么它不起作用,而文档加载项中的类似代码却可以。

标签: c# ms-word interop document save-as


【解决方案1】:

这是一个相当愚蠢的错误...比较' == ".doc" ' 而不是' == "doc"...

我没有注意到它,因为当 SaveAs2 收到扩展名为“.doc”且没有 WdSaveFormat 的文件路径时,它 - 奇怪的是 - 创建了一个 Word 文档文件,该文件存在我在此处解释的问题......

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-26
    相关资源
    最近更新 更多