วิธีสร้างเอกสาร Word โดยใช้ C#

ในบทช่วยสอนนี้ เราจะได้เรียนรู้ วิธีสร้างเอกสาร Word โดยใช้ C# เขียนข้อความด้วยรูปแบบตัวอักษรต่างๆ ใส่ไฮเปอร์ลิงก์ลงในเอกสาร และบันทึกเอกสารเป็นรูปแบบไฟล์ DOCX

ขั้นตอนต่อไปนี้อธิบายวิธีที่ C# สร้างไฟล์เอกสาร Word

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

  1. ติดตั้งแพ็คเกจ Aspose.Words for .NET จาก NuGet
  2. เพิ่มการอ้างอิง Aspose.Words และ Aspose.Words.Saving เนมสเปซ
  3. สร้างอินสแตนซ์ของคลาส Document และ DocumentBuilder
  4. เขียนข้อความและใส่ไฮเปอร์ลิงก์ลงในเอกสาร
  5. บันทึกเอกสารเป็นรูปแบบไฟล์ DOCX

ก่อนหน้านี้ เราตรวจสอบ วิธีแทรกส่วนหัวและส่วนท้ายใน DOCX โดยใช้ C# ตัวอย่างโค้ดต่อไปนี้ใน C# สร้างเอกสาร Word ในรูปแบบไฟล์ DOCX ที่รู้จักกันดี คุณสามารถใช้วิธีการเดียวกันในการสร้างเอกสาร Word ในรูปแบบไฟล์ต่างๆ เช่น DOC, RTF เป็นต้น โดยใช้วิธี Document.Save ตัวอย่างโค้ดนี้สามารถใช้ได้เมื่อติดตั้ง .NET

รหัสเพื่อสร้างเอกสาร Word โดยใช้ C

using System.Drawing;
using Aspose.Words;
using Aspose.Words.Saving;
namespace KBCodeExamples
{
class how_to_create_word_document_using_c_sharp
{
public static void Main(string[] args)
{
//Set Aspose license before creating blank Word document
Aspose.Words.License AsposeWordsLicense = new Aspose.Words.License();
AsposeWordsLicense.SetLicense(@"Aspose.Words.lic");
// Create a blank Word document
Document doc = new Document();
// Initialize a new instance of DocumentBuilder class
DocumentBuilder builder = new DocumentBuilder(doc);
// Insert a string surrounded by a border
builder.Font.Border.Color = Color.Green;
builder.Font.Border.LineWidth = 2.5d;
builder.Font.Border.LineStyle = LineStyle.DashDotStroker;
builder.Write("Text surrounded by green border.");
// Remove all font formatting specified explicitly
builder.Font.ClearFormatting();
builder.InsertBreak(BreakType.ParagraphBreak);
builder.Write("For more information, please visit the ");
// Insert a hyperlink and emphasize it with custom formatting
// The hyperlink will be a clickable piece of text which will take us to the location specified in the URL
builder.Font.Color = Color.Blue;
builder.Font.Underline = Underline.Single;
builder.InsertHyperlink("Aspose Knowledge Base", "https://kb.aspose.com/", false);
builder.Font.ClearFormatting();
builder.Writeln(".");
OoxmlSaveOptions saveOptions = new OoxmlSaveOptions
{
Compliance = OoxmlCompliance.Iso29500_2008_Strict,
SaveFormat = SaveFormat.Docx
};
// Save the document with strict compliance level
doc.Save("create word document using C#.docx", saveOptions);
}
}
}

ตัวอย่างโค้ดข้างต้นใน c# สร้างเอกสาร Word ตั้งแต่เริ่มต้น คลาสเอกสารแสดงถึงเอกสาร Word เปล่า คุณต้องเชื่อมโยง DocumentBuilder กับเอกสาร คุณสามารถใช้ DocumentBuilder เพื่อแทรกเนื้อหาประเภทต่างๆ ลงในเอกสาร Word เช่น ตาราง รูปภาพ ข้อความ เป็นต้น

 ไทย