Posted by: Nishant Rana | November 3, 2007

Creating Word document using C#

Create a new windows application project and add a button to it.

On click of that button, we will create a new document(word) and write a simple Hello World text in it.

To create a word document using C# we need to first reference the following DLL(com)

DLL

After adding reference, add this directive

using Microsoft.Office.Interop.Word;

Put this code on button click

object missing = System.Reflection.Missing.Value;
object Visible=true;
object start1 = 0;
object end1 = 0;
ApplicationClass WordApp = new ApplicationClass();
Document adoc = WordApp.Documents.Add(ref missing, ref missing, ref missing, ref missing);
Range rng=adoc.Range(ref start1,ref missing);
rng.Font.Name=”Georgia”;
rng.InsertAfter(”Hello World!”);
object filename = @”C:\MyWord.doc”;
adoc.SaveAs(ref filename, ref missing, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
WordApp.Visible=true;

Bye

Responses

I have private void mnuManual_Click(object sender, System.EventArgs e)
{
// Opens Word applicationMicrosoft.Office.Interop.
Word.Application word = null;
// Opens new documentMicrosoft.Office.Interop.
Word.Document doc = null;
// Instantiates Word applicationMicrosoft.Office.Interop.
Word = new Word.Application();
// Links to public website where the User Manual is located ( I wanna have the user manual on my desktop as I have not website.
object objFileName= “desktop”

// Keeps User Manual read-only
object objTrueValue = true;
// References to Word class exceptions used when showing error messages
object objMissing = Type.Missing;
// Shows Word application
Word.Visible = true;
// Focuses on Word
Word.Activate();

// Opens file and acts as an exception handler in Word
doc = word.Documents.Open(ref objFileName, ref objMissing, ref objTrueValue,
ref objMissing, ref objMissing, ref objMissing, ref objMissing, ref objMissing,
ref objMissing, ref objMissing, ref objMissing, ref objMissing, ref objMissing,
ref objMissing, ref objMissing, ref objMissing);
// Focuses on User Manual opened in Word application
doc.Activate();

}

My errors are say that” the name ‘doc’ does not exist in the class or namespace. The same is saud for word too. It says I need to reference them.

Creating Word Document is Vey Very Good. Is there any way to OPEN pdf file from Windows Forms?

hi,
Thanks a lot.i search many site and forum for read word doc from asp.net.many site give the samples but it will not work out.this sample is very very useful for me.once again i tell thanks a lot

bye
sampath

Leave a response

Your response:

Categories