word文档中经常会使用脚注和尾注来为文档添加说明。脚注一般位于当前页面的底部或文字下方,用于作为文档某处内容的注释。而尾注一般位于文档的末尾,列出引文的出处等。该文章主要描述如何使用C# 为Word文档添加脚注尾注。
//新建一个word文档对象并加载需要添加脚注尾注的word文档
Document document = new Document();
document.LoadFromFile("Test.docx", FileFormat.Docx2010);
//获取第一个段落
Paragraph paragraph = document.Sections[0].Paragraphs[0];
//添加脚注
Footnote footnote = paragraph.AppendFootnote(FootnoteType.Footnote);
//在第一段里查找字符串“Spire.Doc for .NET” 并用来添加脚注
DocumentObject obj = null;
for (int i = 0; i < paragraph.ChildObjects.Count; i++)
{
obj = paragraph.ChildObjects[i];
if (obj.DocumentObjectType == DocumentObjectType.TextRange)
{
TextRange textRange = obj as TextRange;
if (textRange.Text == "Spire.Doc for .NET")
{
//为添加脚注的字符串设置加粗格式
textRange.CharacterFormat.Bold = true;
//插入脚注
paragraph.ChildObjects.Insert(i + 1, footnote);
break;
}
}
}
//添加脚注内容并设置字体格式
TextRange text = footnote.TextBody.AddParagraph().AppendText("Spire.Doc脚注");
text.CharacterFormat.FontName = "Arial Black";
text.CharacterFormat.FontSize = 10;
text.CharacterFormat.TextColor = Color.DarkGray;
footnote.MarkerCharacterFormat.FontName = "Calibri";
footnote.MarkerCharacterFormat.FontSize = 12;
footnote.MarkerCharacterFormat.Bold = true;
footnote.MarkerCharacterFormat.TextColor = Color.DarkGreen;
//获取第三段落
Paragraph paragraph2 = document.Sections[0].Paragraphs[2];
//添加尾注并设置尾注和格式
Footnote endnote = paragraph2.AppendFootnote(FootnoteType.Endnote);
TextRange text2 = endnote.TextBody.AddParagraph().AppendText("Spire.Doc尾注");
text2.CharacterFormat.FontName = "Arial Black";
text2.CharacterFormat.FontSize = 10;
text2.CharacterFormat.TextColor = Color.DarkGray;
endnote.MarkerCharacterFormat.FontName = "Calibri";
endnote.MarkerCharacterFormat.FontSize = 12;
endnote.MarkerCharacterFormat.Bold = true;
endnote.MarkerCharacterFormat.TextColor = Color.DarkGreen;
//保存文档
document.SaveToFile("添加脚注尾注.docx", FileFormat.Docx2010);
Word脚注尾注效果图: