يستخدم بعض الأشخاص مكتبة Microsoft Office Interop لإنشاء مستندات Word ، ولكنهم غالبًا ما يطرحون السؤال حول كيفية إنشاء مستند Word في C# بدون إمكانية التشغيل المتداخل. هذا هو المكان الذي يلعب فيه Aspose.Words for .NET دورًا للمساعدة في إنشاء مستند Word في C# بسهولة.
تتم الإجابة على هذا السؤال في الخطوات أدناه جنبًا إلى جنب مع نموذج رمز C#. يوضح هذا مدى سهولة وكفاءة إنشاء ملف DOCX أو DOC من البداية في تطبيقات .NET ، سواء كانت أداة مساعدة .NET console أو تطبيق Windows أو مشروع ويب ASP.NET. تعمل Aspose.Words بسلاسة مع كل تقنية منصة .NET.
خطوات إنشاء مستند Word في C# بدون أتمتة
- استخدم حزمة Aspose.Words for .NET NuGet
- أضف مرجعًا إلى Aspose.Words namespace
- استخدم طريقة SetLicense لتطبيق ترخيص Aspose
- قم بإنشاء مثيل Document Class جديد
- قم بإنشاء كائن DocumentBuilder Class وقم بتمرير كائن المستند في المنشئ
- قم بتعيين الخصائص المطلوبة لكائن DocumentBuilder
- احفظ مستند Word الناتج كملف أو دفق
رمز لإنشاء مستند Word في C# بدون أتمتة
using System; | |
//Add reference to Aspose.Words for .NET API | |
//Use following namespaces to Word Document generator code | |
using Aspose.Words; | |
namespace CreateWordDocumentWithoutInterop | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
//Set Aspose license before creating Word document without Interop | |
//using Aspose.Words for .NET | |
Aspose.Words.License AsposeWordsLicense = new Aspose.Words.License(); | |
AsposeWordsLicense.SetLicense(@"c:\asposelicense\license.lic"); | |
//Create an instance of Document class of Aspose.Words for .NET | |
//This initiates a blank Word document | |
Document WordDocumentWithoutInterop = new Document(); | |
//An instance of DocumentBuilder class is used to add | |
//content to the Word Document | |
DocumentBuilder WordDocumentBuilder = new DocumentBuilder(WordDocumentWithoutInterop); | |
//Add some text with bold formatting | |
WordDocumentBuilder.Bold = true; | |
WordDocumentBuilder.Writeln("We're adding this line of text in the word document using DocumentBuilder Class"); | |
WordDocumentBuilder.Writeln("This does not require Office Interop or Office Automation"); | |
//Finally, save the generated word document to docx format | |
WordDocumentWithoutInterop.Save("Word_Document_Created_Without_Interop_using_CSharp.docx"); | |
} | |
} | |
} |
في مثال رمز C# هذا ، أنشأنا Word document بسيطًا من سطرين فقط من النص وتطبيق سمة غامقة على النص. ومع ذلك ، يمكنك القيام بالكثير وتوسيع الكود أعلاه عن طريق إضافة جداول وخلايا وكائنات أخرى مختلفة من Word Document Object Model (DOM).
لتنفيذ كود C# أعلاه من Aspose.Words for .NET API ، لست مطالبًا بتثبيت Microsoft Word على جهاز الكمبيوتر الخاص بك أو الخادم حيث سيتم تثبيت التطبيق. هذا يجعل إنشاء مستند Word أسهل كثيرًا وأسرع.