C#使用FreeSpire.doc生成带有页码的目录
- 互联网
- 2025-09-07 02:33:01

1.使用nuget获取dll。
2.全部代码如下。
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; using Spire.Pdf;
namespace test01 { public partial class Form1 : Form {
private string OpenFilePath;//存储选择到的文件的完整路径
public Form1() { InitializeComponent(); }
private void button1_Click(object sender, EventArgs e) { //免费版本,在加载或操作Word文档时,要求Word文档不超过500个段落和25个表格
// 创建Document类的对象 Document doc = new Document();
string path = OpenFilePath; // 载入Word文档 doc.LoadFromFile(path); // 定义占位符文本,目录后 string placeholderText = "目录";
// 获取文档中的所有节 Spire.Doc.Collections.SectionCollection sections = doc.Sections; Section section = sections[0]; // 遍历节中的每个段落 for (int j = 0 ; j < section.Paragraphs.Count ; j++) { Paragraph paragraph = section.Paragraphs[j]; Console.WriteLine(paragraph.Text);
if (paragraph.Text.Contains(placeholderText)) //需要手动或者代码插入 目录 两个字居中显示,还要换行 { // 在找到占位符的段落后插入目录 // 在新段落中创建一个展示1到3级标题的目录 paragraph.AppendTOC(1, 3); //paragraph.getFormat().setPageBreakAfter(false);
//paragraph.Format.setPageBreakBefore(true); break; } }
// 更新目录 doc.UpdateTableOfContents();
//更新页码 //doc.UpdateTOCPageNumbers();
//doc.TOC doc.SaveToFile(path);
/* //另存为pdf,免费版本的只可以三页 ToPdfParameterList toPdf = new ToPdfParameterList(); toPdf.PdfConformanceLevel = Spire.Doc.PdfConformanceLevel.Pdf_A1B; doc.SaveToFile("result.Pdf", toPdf); */
doc.Dispose(); //todo 如果需要处理空行,则需要全部完成后重新额外在更新一次文档目录 需要重新打开word MessageBox.Show("成功了!!!");
}
private void button2_Click(object sender, EventArgs e) { OpenFileDialog ofd = new OpenFileDialog(); ofd.Title = "浏览";//设置对话框标题栏的内容 ofd.Filter = "文本文件|*docx;*.doc"; //这是设置对话框内显示的指定后缀类型文件(可设置多个) if (ofd.ShowDialog() == DialogResult.OK) { OpenFilePath = ofd.FileName; this.textBox1.Text = OpenFilePath; } else { return; } } } }
C#使用FreeSpire.doc生成带有页码的目录由讯客互联互联网栏目发布,感谢您对讯客互联的认可,以及对我们原创作品以及文章的青睐,非常欢迎各位朋友分享到个人网站或者朋友圈,但转载请说明文章出处“C#使用FreeSpire.doc生成带有页码的目录”