Dec 1, 2008

Microsoft Office Word automation in C# - How to add table to the document?

The following C# code will create a new document, add a table to it and ask the user to save it. Document will look like this:



The following code will add a table in word and then ask the user to provide a filename to save the document:
        Microsoft.Office.Interop.Word.
Application app = new Microsoft.Office.Interop.Word.ApplicationClass();
        app.Visible =
false;

        
object start = 0;
        
object end = 0;
        
object oNull = System.Reflection.Missing.Value;

        
Document doc = new DocumentClass();
        doc = app.Documents.Add(
ref oNull, ref oNull, ref oNull, ref oNull);

        
Table tbl = doc.Tables.Add(doc.Range(ref start, ref end), 10, 2, ref oNull, ref oNull);
        
Random rnd = new Random();
        
for (int i = 0; i < 10; i++)
        {
           tbl.Rows[i + 1].Cells[1].Range.Text =
"Run# :" + ((int)i + 1).ToString();
           tbl.Rows[i + 1].Cells[2].Range.Text =
"Value :" + rnd.Next(0, 2000).ToString();
        }

        
object oFalse = false;
        app.Visible =
true;
        
try
        {
           doc.Save();
        }
        
catch (Exception ex)
        {
          
if (ex.Message.ToLower().IndexOf("command failed") == -1)
           {
            
throw ex;
           }
        }
        app.Quit(
ref oFalse, ref oFalse, ref oFalse);

What we done is to create a new document, a new table, and fill the table with random values.
Seems very easy but not quite sure how well document :).

5 comments:

Shopping Cart said...

Hi,

This blog article is fully help to the users in adding table in micro soft office.I think it is very help full,Especially for those person whose work in their offices.Shopping Cart.

Anonymous said...

Шикарно.
Где rss лента?

Anonymous said...

Где тут можно подписаться на rss ленту?

Павелъ Дончевъ said...

On the right, there is a label that says:

"Subscribe to my blog ->"

Anonymous said...

Прочитал статью до конца, спасибо большое )))