در این آموزش، چگونه با استفاده از C# سند Word ایجاد کنیم، متنی با فونت های مختلف بنویسیم، یک لینک در آن قرار دهیم و سند را در قالب فایل DOCX ذخیره کنیم.
مراحل زیر توضیح می دهد که چگونه *C# فایل سند Word ایجاد می کند.
مراحل ایجاد سند Word با استفاده از سی شارپ
- بسته Aspose.Words for .NET را از NuGet نصب کنید
- مرجع Aspose.Words و Aspose.Words.Saving فضاهای نام را اضافه کنید
- نمونه ای از کلاس های Document و DocumentBuilder ایجاد کنید
- مقداری متن بنویسید و هایپرلینک را در سند وارد کنید
- سند را در فرمت فایل DOCX ذخیره کنید
قبلاً، نحوه درج هدر و پاورقی در DOCX با استفاده از سی شارپ را بررسی کردیم. مثال کد زیر در C# سند Word را در قالب فایل معروف DOCX ایجاد می کند. شما می توانید از همین رویکرد برای ایجاد سند Word در فرمت های مختلف فایل مانند DOC، RTF و غیره با استفاده از روش Document.Save استفاده کنید. این مثال کد را می توان در جایی که دات نت نصب شده است استفاده کرد.
کد برای تولید سند Word با استفاده از سی شارپ
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 را با Document مرتبط کنید. می توانید از DocumentBuilder برای درج انواع مختلف محتوا در سند Word مانند جدول، تصاویر، متن و غیره استفاده کنید.