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


Discover more from Nishant Rana's Weblog

Subscribe to get the latest posts sent to your email.

Unknown's avatar

Author: Nishant Rana

I love working in and sharing everything about Microsoft.NET technology !

74 thoughts on “Creating Word document using C#”

  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.

    Like

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

    Like

  3. 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: 0x8001010A (RPC_E_SERVERCALL_RETRYLATER))

    Like

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

    Like

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

    Like

  6. 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”;
    ..

    Like

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

    Like

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

    Like

  9. 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…

    Like

  10. @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.

    Like

  11. Dear Nishant Rana,

    When i deploy this code on iis. This code start the process of Word but it did not show word on screen.
    If i run this in visual studio it work fine. Please help me as soon as possible.

    Regards

    Shahbaz Sajjad

    Like

  12. Dear Nishant Rana,

    Is there a way to create items in the table of contents that link to the actual item in the page(page 1, page 2, page 3, etc)

    Like

    1. Dear Nishant Rana,

      Thank you for that post, it was helpful. I am having two issues with the table of contents. The first thing is the positioning of table of contents, I need it to go on the top of the page. It currently goes to the end of the page right now. Also, I am having an issue with the headers and subheaders being displayed in the table of contents. For instance, if I have a paragraph with a heading, I only want the heading to display in the table of contents, not the acutal contents of the paragraph.

      Thanks,

      J

      Like

  13. Hello,
    This is nice article.
    But I want to save the particular content of the word to other file format such as .txt, .html, .docx and html source code.
    Particular content means e.g. I am having one table of 1 row and 1 column in word file, and i want to save this table’s content to other file format. Only the table’s content I want to save. Please help me if you have any solution for that. Thanking You 🙂

    Like

  14. Hi.
    I like this blogpost. It was nice to read.
    I am curious how come I didn’t find this blog earlier.

    I will surely share. Some of my Facebook friends will like this.

    Thanks and keep up the good work!
    🙂

    Like

  15. Hai
    I am getting problem on copying these lines from the above code plzzzzzzzz help me

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

    Like

  16. Im using VB.6, this code to export data in datagrid to word 2003 or 2007;

    _____________________________________________________
    ‘WORD
    A_1.Recordset.MoveFirst
    Dim Word As Word.Application
    Jumlah = A_1.Recordset.RecordCount
    Set Word = CreateObject(“word.Application”)
    Word.Documents.Add
    Word.Documents(1).Tables.Add Word.Documents(1).Range, Jumlah, 7
    For i = 1 To Jumlah
    Word.Documents(1).Tables(1).Cell(i, 1).Range.InsertAfter A_1.Recordset(0)
    Word.Documents(1).Tables(1).Cell(i, 2).Range.InsertAfter A_1.Recordset(1)
    Word.Documents(1).Tables(1).Cell(i, 3).Range.InsertAfter A_1.Recordset(2)
    Word.Documents(1).Tables(1).Cell(i, 4).Range.InsertAfter A_1.Recordset(3)
    Word.Documents(1).Tables(1).Cell(i, 5).Range.InsertAfter A_1.Recordset(4)
    Word.Documents(1).Tables(1).Cell(i, 6).Range.InsertAfter A_1.Recordset(5)
    Word.Documents(1).Tables(1).Cell(i, 7).Range.InsertAfter A_1.Recordset(6)
    A_1.Recordset.MoveNext
    Text9.Text = A_1.Recordset.AbsolutePosition
    Next i
    Word.Visible = True
    A_1.Recordset.MoveFirst

    __________________________________________
    in before time, add in references “Microsoft Word 11.0 object library” to word 2003, or “Microsoft Word 12.0 object library” to word 2007. Good Luck…….

    Like

  17. Hi,
    aDoc = wordApp.Documents.Open(ref filename, ref missing, ref readOnly, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref isVisible, ref missing, ref missing, ref missing);

    this doesn’t work in IIS for me.
    I have made all the changes dcomconfig security settings

    The website becomes non responsive.

    (Exception type: COMException
    Exception message: The remote procedure call failed. (Exception from HRESULT: 0x800706BE)
    at Word.Documents.Open(Object& FileName, Object& ConfirmConversions, Object& ReadOnly, Object& AddToRecentFiles, Object& PasswordDocument, Object& PasswordTemplate, Object& Revert, Object& WritePasswordDocument, Object& WritePasswordTemplate, Object& Format, Object& Encoding, Object& Visible, Object& OpenAndRepair, Object& DocumentDirection, Object& NoEncodingDialog))

    Please find me any solution you have
    thanks in advance.

    Like

  18. i’m having troubles when i add more than one hyperlink, could you help me i’m using something like this

    Range rango = oDoc.Range(ref oStartRange, ref oMissing);
    rango.InsertAfter(“I. ” + descriNodo);
    Object address = “www.google.com”;
    Object screenTip = “Search on google”;
    rango.Hyperlinks.Add(rango, ref address, ref oMissing, ref screenTip, ref oMissing, ref oMissing);
    rango.InsertParagraphAfter();

    ….

    ///more code here

    Range rng = oDoc.Range(ref oStartRange, ref oEndRange);
    rng.InsertAfter(relacion.Descripcion);
    Object direccion = “www.microsoft.com”;
    Object toolTip = “Microsoft”;

    //rng.InsertParagraphBefore();
    rng.Hyperlinks.Add(rng, ref direccion, ref oMissing, ref toolTip, ref oMissing, ref oMissing);
    rng.ParagraphFormat.LeftIndent = 85;

    dat.Range.InsertParagraphAfter();

    In Word i only have the textline of

    Search in google

    But the link is the one of Microsoft

    Please help!!

    Like

  19. Hi Nishanth …. Thanx for ur posts … I want a small help… My problem is i want to read thing me word doc(Including shapes) … I have tried some of the ways but its giving me upto to read only text …..

    Can u please??

    Like

  20. I have the error like word was unable to read this document. it may be corrupt
    try one or more following
    1.open and repair the file

    This is already open datareader associated with this command must be closed first.

    .could you give solution now. Thanks in advance

    N.sanmugavel

    Like

  21. Hi Nishanth,

    Thanx for your post. It helped us build our own simple engine for genarating document. We took approach of using bookmarks for placeholders. It worked great until we realized that it is causing problems, such as spontaneous COM errors. Our customers had so much problems with the solution that we started to look around and found out that the better way is to use Microsoft’s Open XML SDK.

    We started to build a new engine based on Open XML parser, but then we found out that there are products on the market that do not need the presence of Office Word. We now use the document generation solution from http://www.Docentric.com which is exactly what we needed.

    Event if we were to build our custom solution, we would probably use the Open XML SDK.

    P.Bruce

    Like

  22. If anyone gets the following message

    “Error: Interop type ‘Microsoft.Office.Interop.Word.ApplicationClass’ cannot be embedded. Use the applicable interface instead.”

    here’s what you should do. Change the line

    ApplicationClass WordApp = new ApplicationClass();

    to

    Microsoft.Office.Interop.Word.Application WordApp = new Microsoft.Office.Interop.Word.Application();

    Like

  23. I have gone through the same procedure everything was working fine but when i published the site the code written is not working dont know why

    Like

  24. Very nice and informative article that beautifully elaborate the basics idea of creating word document using c#. This post helped me lot in understanding creating ms-word document using c# code. Check this link too its having wonderful post with great explanation over the internet on reading ms-word document using c# code….

    http://www.mindstick.com/Articles/5cd1b721-9b94-4ea0-bd6e-2bb157401069/?Read%20Microsoft%20Word%20Document%20File%20by%20using%20C#

    Like

  25. The other day, while I was at work, my sister stole
    my iPad and tested to see if it can survive a 30 foot drop, just so she can be a youtube
    sensation. My apple ipad is now destroyed and she has 83 views.
    I know this is entirely off topic but I had to share it with
    someone!

    Like

Leave a reply to saurabh mahajan Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from Nishant Rana's Weblog

Subscribe now to keep reading and get access to the full archive.

Continue reading

Power Platform Puzzles

D365 CRM, Power Platform Tips &Tricks

Power Spark

Power Spark By Shrangarika

Van Carl Nguyen

Exploration of Power Platform

My Trial

It is my experience timeline.

Power⚡Thomas

Sharing my knowledge and experience about the Microsoft Power Platform.

Arpit Power Guide

a guide to powering up community

Welcome to the Blog of Paul Andrew

Sponsored by Cloud Formations Ltd

Deriving Dynamics 365

Deriving Solutions and features on Power Platform/Dynamics 365

The CRM Ninja

Thoughts & musings from a Microsoft Business Applications Ninja!

D CRM Explorer

Learn about Microsoft Dynamics CRM Power Platform customization and implementation and other cool stuffs

Stroke // Jonas Rapp

I know pre-stroke. I will improve who I was.

Power Melange

Power Melange By Shalinee

Clavin's Blog - PPUG.ORG

AI - Power Automate - Power Apps - SharePoint Online - Azure - Nintex - K2 - Artificial Intelligence

Sat Sangha Salon

An Inquiry in Being

The Indoencers

The Influencers & Influences of Indian Music

Monika Halan's blog

Hand's-free money management

D365 Demystified

A closer look at Microsoft Dynamics 365.

Microsoft Mate (msftmate) - Andrew Rogers

Experienced consultant primarily focused on Microsoft Dynamics 365 and the Power Platform

Manmit Rahevar's Blog

One Stop Destination for Microsoft Technology Solutions

MG

Naturally Curious

Brian Illand

Power Platform and Dynamics 365

Steve Mordue

The Professional Paraphraser

Subwoofer 101

Bass defines your home theater

SQLTwins by Nakul Vachhrajani

SQL Server tips and experiences dedicated to my twin daughters.

Everything D365

Discovering Azure DevOps and D365 Business Applications

Tech Wizard

Lets do IT Spells

XRM Tricks (Power Platform & Dynamics CRM )

Power Platform & Dynamics CRM

CRM TIPS BY PRM

Mail to crmtipsbyprm@gmail.com for queries and suggestions

nijos.dev

Giving back to the community what I have learned

Power Platform Learning

Your Go-To Resource for Power Apps, Power Automate & More

xrm CRM Dynamics

Dynamics CRM Technical & Functional Info

Dynamics 365 Blogs - Explained in unique way

Sometimes you need to look at things from different perspective.