แทรกสารบัญใน Word โดยใช้ C#

แทรกสารบัญใน Word โดยใช้ C# โดยทำตามบทความสั้นๆ นี้ ช่วยสร้างสภาพแวดล้อมโดยการแบ่งปันทรัพยากรที่จำเป็น รายการขั้นตอนในการเขียนแอปพลิเคชัน และโค้ดตัวอย่างที่สาธิต วิธีเพิ่มหน้าเนื้อหาใน Word โดยใช้ C# คุณจะได้เรียนรู้การเพิ่ม TOC ลงในไฟล์ Word ที่มีอยู่โดยการแยกวิเคราะห์เนื้อหา

ขั้นตอนในการสร้างสารบัญใน Word โดยใช้ C#

  1. ตั้งค่าสภาพแวดล้อมเพื่อใช้ Aspose.Words for .NET เพื่อแทรก TOC
  2. โหลดไฟล์ Word ลงในวัตถุ Document และเริ่มต้นวัตถุ DocumentBuilder
  3. เพิ่มชื่อเรื่อง TOC ด้วยสไตล์ที่ต้องการ
  4. แทรกสารบัญและแทรกตัวแบ่งหน้า
  5. เติมสารบัญว่าง
  6. บันทึกไฟล์ Word เอาท์พุตที่มี TOC อยู่ในนั้น

คุณสามารถ แทรกหน้าเนื้อหาใน Word โดยใช้ C# ได้ด้วยความช่วยเหลือของขั้นตอนเหล่านี้ เริ่มต้นกระบวนการโดยการโหลดไฟล์ Word และกำหนดค่าออบเจ็กต์คลาส DocumentBuilder ที่รองรับการเพิ่มสารบัญ เพิ่มชื่อเรื่องและสารบัญโดยใช้เมธอด InsertTableOfContents() และเติมสารบัญว่างโดยการเรียกเมธอด UpdateFields()

รหัสเพื่อสร้างสารบัญใน Word โดยใช้ C#

using System;
using Aspose.Words;
class Program
{
static void Main(string[] args) // Insert table of contents in Word using C#
{
new License().SetLicense("License.lic");
// Load the document
Document doc = new Document("example03.docx");
// Instantiate the DocumentBuilder object
DocumentBuilder builder = new DocumentBuilder(doc);
// Create ParagraphFormat object
ParagraphFormat paragraphFormat = builder.ParagraphFormat;
// Store the existing style name
string defaultStyle = paragraphFormat.StyleName;
// Set style name and text alignment for the table of contents
paragraphFormat.StyleName = "Title";
paragraphFormat.Alignment = ParagraphAlignment.Center;
// Add title of TOC
builder.Writeln("Table of contents");
// Restore the text style
paragraphFormat.StyleName = defaultStyle;
// Insert a table of contents
builder.InsertTableOfContents("\\o \"1-3\" \\h \\z \\u");
// Insert page break for TOC
builder.InsertBreak(BreakType.PageBreak);
// Populate the empty table of contents
doc.UpdateFields();
// Save document with TOC
doc.Save("output.docx");
Console.WriteLine("Done");
}
}

ใช้โค้ดนี้เพื่อ สร้างหน้าเนื้อหาใน Word โดยใช้ C# InsertTableOfContents() ต้องใช้สวิตช์เพื่อควบคุมพฤติกรรมของสารบัญ เช่น 1-3 ใช้สำหรับระบุหัวเรื่อง 1, 2 และ 3, ‘\h’ สำหรับการใช้ไฮเปอร์ลิงก์ และ ‘\u’ สำหรับการตั้งค่าระดับเค้าร่าง TOC เริ่มต้นว่างเปล่าและกรอกโดยใช้เมธอด UpdateFields()

บทความนี้สอนเรา วิธีเพิ่มสารบัญใน Word โดยใช้ C# หากต้องการแทรกส่วนหัวและส่วนท้าย โปรดดูบทความเกี่ยวกับ วิธีแทรกส่วนหัวและส่วนท้ายใน DOCX โดยใช้ C #

 ไทย