web
You’re offline. This is a read only version of the page.
close
Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
Dynamics 365 Community / Blogs / Nishant Rana’s Weblog / Creating Word document usin...

Creating Word document using C#

Nishant Rana Profile Picture Nishant Rana 11,325 Microsoft Employee

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

    private void button1_Click(object sender, EventArgs e)
        {
            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);
 
            try
            {              
                rng.Font.Name = “Georgia”;
                rng.InsertAfter(“Hello World!”);
                object filename = @”D:\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;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }        
        }
The easiest way to write code for office interoperability is to make use of VBA code.

Say you want to insert a picture in a word document what you can do is

open the word document – Go to Tools ->Macro-> Record New Macro

Now click on insert menu and insert the picture. Stop the recording, again go to Macro -Macros-> Select your Macro and click on edit

You will find the vba code over there

Sub Macro1()

Selection.InlineShapes.AddPicture FileName:= _
“C:\Documents and Settings\nishantr1\My Documents\My Pictures\untitled.bmp” _
, LinkToFile:=False, SaveWithDocument:=True
End Sub

Now to write the same code in c# you will do something like this

Range rngPic = adoc.Tables[1].Range;
rngPic.InlineShapes.AddPicture(@”C:\anne_hathaway.jpg”, ref missing, ref missing, ref missing);

Bye



This was originally posted here.

Comments

*This post is locked for comments