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

    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


Responses

  1. 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.

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

  3. 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

  4. Hi Nishant,

    This code workd 4 me..

    Thnks a tonn :)

  5. Hi nishant,

    I have done exactly same what you have suggested here but i am getting error as follows
    The message filter indicated that the application is busy. (Exception from HRESULT: 0×8001010A (RPC_E_SERVERCALL_RETRYLATER))

  6. i want to write a program using C# that i can read and write microsoft word from sql server.

  7. I have the same problem that Nilesh.

    I’m writing a small program to convert wordML’s in pdf using a WS. The problem is that server, who executes office code return the error:

    The message filter indicated that the application is busy. (Exception from HRESULT: 0×8001010A (RPC_E_SERVERCALL_RETRYLATER))

    I know that main problem is of permissions over ASPNET user.

    I try to assign permissions over office COM component using service component but not works.

    Too adding permissions in all folders that my process write to ASPNET, IWAM and IUSR users but not works…

    Somebody have any idea? thx

  8. Test

  9. Is there a way to Hyperlink “Hello World” to a file or directory?

    The code worked the first time with Office 2007 and the 12.0 library.

    Thanks for the post.

  10. Hi Steve,
    I guess you want to add hyperlink to the Hello World text.
    You can do something like this

    Range rng=adoc.Range(ref start1,ref missing);
    rng.Font.Name=”Georgia”;
    rng.InsertAfter(“Hello World!”);

    Object address = @”http://www.google.co.in”;
    Object screenTip = “Go to google search page”;
    rng.Hyperlinks.Add(rng, ref address, ref missing, ref screenTip, ref missing, ref missing);

    object filename = @”C:\MyWord.doc”;
    ..

  11. try to use template-driven rendering like aspose.word or invoke docx lib ( http://www.invoke.co.nz/products/docx.aspx ). You’ll specify all text properties in document and will fill in content only. Aspose is more heavy and powerful (and expensive :)), invoke is simpler but much easier and free

    COM sux, both libs are pure .net

  12. Nishant, Is there a simple way to add an image into a newly created Word Document?

  13. Hi Atul,
    Check out this post of mine

    http://nishantrana.wordpress.com/2008/07/17/opening-and-inserting-a-picture-in-word-document-programmatically-using-c/

  14. Hi Nishant,
    Is there any way to create a word document like an application form, in which I will fill the content of form using varibles ?
    i.e. I am having an application form in word document; I want to fill it using array of objects & create multiple word documents. How to do it?

  15. how to insert file into .doc ?

  16. Hi,

    How to implement C# code to create Word File using macro?

    Please help me to create a word file uisng following macro.
    Sub Macro1()
    Selection.TypeText Text:=”Reference No.: B1729″
    Selection.TypeParagraph
    Selection.TypeParagraph
    Selection.TypeText Text:=”Name: FirstName MiddleName LastName”
    Selection.TypeParagraph
    Selection.TypeParagraph
    Selection.TypeText Text:=”Date Of Birth: dd-mmm-yyyy”
    Selection.TypeParagraph
    Selection.TypeParagraph
    Selection.TypeText Text:=”Address:”
    Selection.TypeParagraph
    With Selection.ParagraphFormat
    .LeftIndent = InchesToPoints(0.63)
    .SpaceBeforeAuto = False
    .SpaceAfterAuto = False
    End With
    With Selection.ParagraphFormat
    .SpaceBeforeAuto = False
    .SpaceAfterAuto = False
    .FirstLineIndent = InchesToPoints(-0.63)
    End With
    With Selection.ParagraphFormat
    .SpaceBeforeAuto = False
    .SpaceAfterAuto = False
    .FirstLineIndent = InchesToPoints(0)
    End With
    Selection.TypeText Text:=”Block No, Society”
    Selection.TypeParagraph
    Selection.TypeText Text:=”Area, Area Code”
    Selection.TypeParagraph
    Selection.TypeText Text:=”City, State”
    Selection.TypeParagraph
    With Selection.ParagraphFormat
    .LeftIndent = InchesToPoints(0)
    .SpaceBeforeAuto = False
    .SpaceAfterAuto = False
    End With
    Selection.TypeParagraph
    End Sub

    Regards,
    Aniket A. Salunkhe

  17. Thanks

  18. Thanks it helped me :)

  19. hi
    for witch version of c# is this code
    i am trying to do this but when i add using directive there is no interop…

  20. hi thanks nice code .
    plz provide me reference to use table in word.

  21. @Nishant: thanks for the very helpful article.

    @Oscar:
    try adding at the end of code:

    WordApp.Quit(ref missing, ref missing, ref missing);
    WordApp = null;

    If that doesn’t help try removing Word.App.Visible line.

  22. Excellent work !!!!!!!
    Thanks a lot, solved my problem just in a second….

  23. [...] http://www.c-sharpcorner.com/UploadF…romDotNet.aspx http://nishantrana.wordpress.com/200…ument-using-c/ [...]


Leave a response

Your response:

Categories