使用Interop更改某些单词文档的脚注编号失败

本文关键字:文档 脚注 编号 失败 单词 Interop 使用 | 更新日期: 2023-09-27 18:25:04

我安装了Word 2016使用的以下代码,引用Microsoft Word 16.0 Object Library:

private void RefreshFootnoteNumbering(FileManagement.FileManager FileManager)
{
    Console.WriteLine(DateTime.Now.ToString() + " Refreshing footnotes DOCX");
    // Opening and saving in word generates the required element
    var Word = GetWordApp();
    try
    {
        var DocxPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Path.ChangeExtension(FileManager.HtmlFileLocation, "docx"));
        Console.WriteLine(DateTime.Now.ToString() + "'tOpening document");
        var Doc = GetWordDoc(Word, DocxPath);
        try
        {
            // Fails on these lines below (both cause the same exception)
            Doc.Footnotes.NumberingRule = InteropWord.WdNumberingRule.wdRestartPage;
            Doc.Footnotes.Location = InteropWord.WdFootnoteLocation.wdBottomOfPage;
            Doc.SaveAs2(DocxPath, InteropWord.WdSaveFormat.wdFormatXMLDocument, AddToRecentFiles: false, EmbedTrueTypeFonts: true);
        }
        finally
        {
            Doc.Close();
            Doc = null;
        }
    }
    finally
    {
        Word.Quit();
        Word = null;
        GC.Collect();
        GC.WaitForPendingFinalizers();
    }
}

这适用于大多数文档,但对于一些文档,我会得到以下例外:

System.Runtime.InteropServices.COMException was unhandled
  ErrorCode=-2146823680
  HResult=-2146823680
  HelpLink=wdmain11.chm#37376
  Message=Value out of range
  Source=Microsoft Word
  StackTrace:
       at Microsoft.Office.Interop.Word.Footnotes.set_NumberingRule(WdNumberingRule prop)

其他互操作函数(迭代/操作字段、节等)运行良好,似乎只是以这种方式更改脚注,但存在问题。从Word内部修改它们效果很好。

以前有人遇到过这个问题吗?有什么解决办法或替代方案吗?


我试着录制了一个宏,它给出了以下VBA代码:

With ActiveDocument.Range(Start:=ActiveDocument.Content.Start, End:= _
    ActiveDocument.Content.End).FootnoteOptions
    .Location = wdBottomOfPage
    .NumberingRule = wdRestartContinuous
    .StartingNumber = 1
    .NumberStyle = wdNoteNumberStyleArabic
    .NumberingRule = wdRestartPage
    .LayoutColumns = 0
End With

如果我运行这个宏,无论我是从调试器运行,还是只是查看宏->运行,我都会在.Location行上得到相同的错误(值超出范围,错误编号4608)。

我还试着把VBA翻译成C#代码:

var Options = Doc.Range(Doc.Content.Start, Doc.Content.End).FootnoteOptions;
Options.Location = InteropWord.WdFootnoteLocation.wdBottomOfPage;
Options.NumberingRule = InteropWord.WdNumberingRule.wdRestartPage;

然而,这给出了相同的错误。

使用Interop更改某些单词文档的脚注编号失败

仍然不确定确切的原因(可能是我的代码中创建了不同的部分);仍然不清楚为什么当word记录宏时它工作,但在运行它时却不工作。

无论如何,我设法将C#代码更改为以下代码,这似乎完成了任务,而且确实有效!

foreach(InteropWord.Footnote FootNote in Doc.Footnotes)
{
    FootNote.Reference.FootnoteOptions.NumberingRule = InteropWord.WdNumberingRule.wdRestartPage;
    FootNote.Reference.FootnoteOptions.Location = InteropWord.WdFootnoteLocation.wdBottomOfPage;
}