1

I want to create a word document with html content in c#. But the following code shows the content as a text only not html formating...

Here is my code:

Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();  
              app.Visible=true;

              object template = Missing.Value;
              object newTemplate = Missing.Value;
              object documentType = Missing.Value;
              object visible = true;  //Show the doc while we work.
              _Document doc = app.Documents.Add(ref template,
                       ref newTemplate,
                       ref documentType,
                       ref visible);   
            doc.Words.First.InsertBefore ("<html><body>HTML content here!</body></html>");
3
  • 1
    Why would Word think it is HTML ? What is you wanted to show <p> ? Commented Aug 14, 2013 at 11:11
  • Actually I will put some tables as the word content and I am using html to format the body. This part "<html><body>HTML content here!</body></html>" is only example.. Commented Aug 14, 2013 at 11:25
  • I think there must be a property to specify the content type is html but I could not find it. Commented Aug 14, 2013 at 11:27

1 Answer 1

3

You might use a HTML file as the source:

using System;
using System.IO;
using System.Reflection;
using Microsoft.Office.Interop.Word;
using System.Windows.Forms;

class Program
{
    [STAThread]
    public static void Main()
    {
        var file = new FileInfo("input.html");
        Microsoft.Office.Interop.Word.Application app 
            = new Microsoft.Office.Interop.Word.Application();
        try
        {
            app.Visible = true;
            object missing = Missing.Value;
            object visible = true;
            _Document doc = app.Documents.Add(ref missing,
                     ref missing,
                     ref missing,
                     ref visible);
            var bookMark = doc.Words.First.Bookmarks.Add("entry");
            bookMark.Range.InsertFile(file.FullName);
        }
        catch (Exception)
        {
            throw;
        }
        finally
        {
            app.Quit();
        }
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

doc.Words.First.Bookmarks.Add("entry"); this part gives error? You say that, I must write the content to a file then read?
Adding the HTML to a file and then inserting the file into the word document worked for me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.