none
要生成多級嵌套的標題,在word中,用C#怎麼寫? RRS feed

  • 问题

  • 問題就如題目,如何實現呢?

    要得到類似這樣的多級嵌套: 
    1. One 
    2. Two 
    2.1 TwoPointOne 
    2.2 TwoPointTwo 
    2.2.1 TwoTwoOne 
    3. Three 

    2015年4月15日 1:59

答案

  • 這裡有篇文章你可以參考來實現。

    定義一個多級列表樣式,再建一個段落,在段落中添加文字和其他內容,并應用段落樣式Heading1,然後根據需要進行重複。

    Document document = new Document();
    Section section = document.AddSection();
    
    ListStyle listStyle = new ListStyle(document, ListType.Numbered);
    listStyle.Name = "levelstyle";
    listStyle.Levels[0].PatternType = ListPatternType.Arabic;
    listStyle.Levels[1].NumberPrefix = "\x0000.";
    listStyle.Levels[1].PatternType = ListPatternType.Arabic;
    listStyle.Levels[2].NumberPrefix = "\x0000.\x0001.";
    listStyle.Levels[2].PatternType = ListPatternType.Arabic;
    document.ListStyles.Add(listStyle);
    
    Paragraph paragraph = section.AddParagraph();
    paragraph.AppendText("The first item");
    paragraph.ApplyStyle(BuiltinStyle.Heading1);
    paragraph.ListFormat.ApplyStyle("levelstyle");
    
    paragraph = section.AddParagraph();
    paragraph.AppendText("The second item");
    paragraph.ApplyStyle(BuiltinStyle.Heading1);
    paragraph.ListFormat.ApplyStyle("levelstyle");
    
    paragraph = section.AddParagraph();
    paragraph.AppendText("The first sub-item");
    paragraph.ApplyStyle(BuiltinStyle.Heading2);
    paragraph.ListFormat.ListLevelNumber = 1;
    paragraph.ListFormat.ApplyStyle("levelstyle");
    
    paragraph = section.AddParagraph();
    paragraph.AppendText("The second sub-item");
    paragraph.ApplyStyle(BuiltinStyle.Heading2);
    paragraph.ListFormat.ContinueListNumbering();
    paragraph.ListFormat.ApplyStyle("levelstyle");
    
    paragraph = section.AddParagraph();
    paragraph.AppendText("A sub-sub-item");
    paragraph.ApplyStyle(BuiltinStyle.Heading5);
    paragraph.ListFormat.ListLevelNumber = 2;
    paragraph.ListFormat.ApplyStyle("levelstyle");
    
    paragraph = section.AddParagraph();
    paragraph.AppendText("The third item");
    paragraph.ApplyStyle(BuiltinStyle.Heading1);
    paragraph.ListFormat.ApplyStyle("levelstyle");
    
    document.SaveToFile(@"result.docx", FileFormat.Docx);

    2015年4月15日 2:10