簡體   English   中英

按字母順序對目錄進行排序

[英]Sort Table of Contents in alphabetical order

我正在使用GemBox.Document創建通過組合多個文檔生成的 Word 文檔,並且在開頭插入 TOC 元素(目錄)。 現在我需要按字母順序排列那個 TOC 元素。

我知道 Microsoft Word 中不存在此選項,TOC 始終按頁面順序排序,而不是按字母順序排序,並且默認情況下TableOfEntries.Update()方法的行為與此類似。

不過,我希望有辦法做到這一點。 我確實檢查了那些 TOC 開關,如果我沒有遺漏什么,就沒有開關,對吧?

最后,我知道索引表,但這不是我想要的。 TOC 元素更適合我想要得到的東西,但我需要它按字母順序排序。

您可以在更新 TOC 元素后“手動”對 TOC 條目進行排序,如下所示:

var document = DocumentModel.Load("input.docx");

var toc = (TableOfEntries)document.GetChildElements(true, ElementType.TableOfEntries).First();
toc.Update();

// Take current TOC entries.
var entries = toc.Entries.ToList();

// Remove them.
toc.Entries.Clear();

// Then place them back in sorted order.
entries.Sort((e1, e2) => e1.Content.ToString().CompareTo(e2.Content.ToString()));
entries.ForEach(e => toc.Entries.Add(e));

document.Save("output.docx");

但請注意,當再次更新 TOC 元素時,無論是使用 GemBox.Document 還是使用某些 Word 應用程序,您都會得到未排序的條目。

您在這里唯一可以做的就是防止其他人更新您的 TOC 元素,例如通過刪除 TOC 並僅保留其條目(也就是取消鏈接目錄):

toc.Content.Set(toc.Entries.Content);

或者您可以將 TOC 放在受保護的部分中,從而防止 Word 應用程序更新 TOC(請注意,您仍然可以使用 GemBox.Document 更新它):

// You mentioned that you're inserting the TOC element at the beginning
// which means that the "toc.Parent" should be document's first Section.
var section = document.Sections[0];

// If TOC is not the only element in a section then place it inside its own section.
if (section.Blocks.Count > 1)
{
    var tocSection = new Section(document);
    tocSection.PageSetup = section.PageSetup.Clone();
    tocSection.Blocks.Add(toc.Clone(true));

    document.Sections.Insert(0, tocSection);
    section.PageSetup.SectionStart = SectionStart.Continuous;
    toc.Content.Delete();
}

document.Protection.StartEnforcingProtection(EditingRestrictionType.FillingForms, "optional password");

// Unprotect all other Sections except the on that contains TOC element.
foreach (var otherSection in document.Sections.Skip(1))
    otherSection.ProtectedForForms = false;

暫無
暫無

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

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