我正在使用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打开它并选择SaveAs时,默认的保存格式是DOCX!) .
如何以真实的文档-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");
1 回答
这是一个相当愚蠢的错误...比较'==“ . doc”'而不是'==“doc”......
我没有注意到它,因为当SaveAs2收到扩展名为“.doc”且没有WdSaveFormat的文件路径时,它 - 奇怪的是 - 创建了一个Word文档文件,其中有我在这里解释的问题...