In C# you can easily create the Microsoft Word document, you can write the content to ms word file and you can save the file programmatically. To create the Microsoft word file .Net providing the Microsoft.Office.Interop.Word library to work with Microsoft Word documents.
In this article we discuss how to create the ms word document, how to write content to document and how to save the document by using C#.
To work with Microsoft Word documents first we have to add reference to the Microsoft.Office.Interop.Word dll as shown below.
Now import the Microsoft.Office.Interop.Word library by using "using" statement. By using Document class of Microsoft.Office.Interop.Word library we can create the ms word document as shown below.
using System;
using System.Diagnostics;
using System.Reflection;
using System.Windows.Forms;
using Microsoft.Office.Interop.Word;
namespace CSharpMSWordExp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
object objMissingVal = Missing.Value;
object Visible = true;
object objStart = 0;
object objFile = System.Windows.Forms.Application.StartupPath + "\\MSWordFile.docx";
ApplicationClass objWordApp = new ApplicationClass();
Document objDoc = objWordApp.Documents.Add(ref objMissingVal, ref objMissingVal, ref objMissingVal, ref objMissingVal);
Range objRange = objDoc.Range(ref objStart, ref objMissingVal);
try
{
objRange.Font.Name = "Arial";
objRange.Font.Size = 12;
objRange.InsertAfter(txtContent.Text);
objDoc.SaveAs(ref objFile, ref objMissingVal, ref objMissingVal, ref objMissingVal, ref objMissingVal, ref objMissingVal,
ref objMissingVal, ref objMissingVal, ref objMissingVal, ref objMissingVal, ref objMissingVal, ref objMissingVal, ref objMissingVal, ref objMissingVal, ref objMissingVal, ref objMissingVal);
objDoc.Close(ref objMissingVal, ref objMissingVal, ref objMissingVal);
Process.Start(objFile.ToString());
}
catch (Exception ex)
{
throw ex;
}
}
}
}
By using Range class we can provide the font name, font size. As shown above we created the ms word document and save the file by using SaveAs() method. After writing the content close the document by using Close() method of Document class. Open the Microsoft Word document by using Start() method of Process class.
Run the application and enter the content in the textbox and click on the button and output is as shown below.
You can purchase the Microsoft Office with greate discounts by using Microsoft Office Promo Code.