About Me

My photo
Ireland
Hello, my name is Cathal Coffey. I am best described as a hybrid between a developer and an adventurer. When I am not behind a keyboard coding, I am hiking and climbing the beautiful mountains of my home country Ireland. I am a full time student studying Computer Science & Software Engineering at the National University of Ireland Maynooth. I am finishing the final year of a 4 year degree in September 2009. I am the creator of an open source project on codeplex.com called DocX. At the moment I spend a lot of my free time advancing DocX and I enjoy this very much. My aim is to build a community around DocX and add features based on requests from this community. I really enjoy hearing about how people are using DocX in their work\personal projects. So if you are one of these people, please send me an email. Cathal coffey.cathal@gmail.com

Friday, May 28, 2010

DocX and Tables

Create and inserting Tables into documents is easy with DocX.

Simple Table
  1. // Create a document.
  2. using (DocX document = DocX.Create(@"Test.docx"))
  3. {
  4. // Add a Table to this document.
  5. Table t = document.AddTable(2, 3);
  6. // Specify some properties for this Table.
  7. t.Alignment = Alignment.center;
  8. t.Design = TableDesign.MediumGrid1Accent2;
  9. // Add content to this Table.
  10. t.Rows[0].Cells[0].Paragraphs.First().Append("A");
  11. t.Rows[0].Cells[1].Paragraphs.First().Append("B");
  12. t.Rows[0].Cells[2].Paragraphs.First().Append("C");
  13. t.Rows[1].Cells[0].Paragraphs.First().Append("D");
  14. t.Rows[1].Cells[1].Paragraphs.First().Append("E");
  15. t.Rows[1].Cells[2].Paragraphs.First().Append("F");
  16. // Insert the Table into the document.
  17. document.InsertTable(t);
  18. document.Save();
  19. }// Release this document from memory.

The above code will creates a document that looks like the below image.

Untitled

Paragraphs inside Table Cells can of course contain content such as Images, Hyperlinks and custom text styles as in the below example.

Advance Table
  1. // Create a document.
  2. using (DocX document = DocX.Create(@"Test.docx"))
  3. {
  4. // Add a Table to this document.
  5. Table table = document.AddTable(2, 3);
  6. // Add a Hyperlink into this document.
  7. Hyperlink h = document.AddHyperlink("Google", new Uri("http://www.google.com"));
  8. // Add an Image into this document.
  9. Novacode.Image i = document.AddImage(@"Logo.png");
  10. // Create a Picture (Custom View) of this Image.
  11. Picture p = i.CreatePicture();
  12. p.Rotation = 10;
  13. // Specify some properties for this Table.
  14. table.Alignment = Alignment.center;
  15. table.Design = TableDesign.LightShadingAccent2;
  16. // Insert the Table into the document.
  17. Table t1 = document.InsertTable(table);
  18. // Add content to this Table.
  19. t1.Rows[0].Cells[0].Paragraphs.First().AppendHyperlink(h).Append(" is my favourite search engine.");
  20. t1.Rows[0].Cells[1].Paragraphs.First().Append("This text is bold.").Bold();
  21. t1.Rows[0].Cells[2].Paragraphs.First().Append("Underlined").UnderlineStyle(UnderlineStyle.singleLine);
  22. t1.Rows[1].Cells[0].Paragraphs.First().Append("Green").Color(Color.Green);
  23. t1.Rows[1].Cells[1].Paragraphs.First().Append("Right to Left").Direction = Direction.RightToLeft;
  24. t1.Rows[1].Cells[2].Paragraphs.First().AppendPicture(p);
  25. document.Save();
  26. }// Release this document from memory.

The above code will creates a document that looks like the below image.

Untitled2

Happy coding,
Cathal

70 comments:

  1. how can i set a row header?
    I have to repeat a row every page.
    thanks

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. Great post Corners :-bd
    I can add row dynamically

    ReplyDelete
  4. This comment has been removed by the author.

    ReplyDelete
  5. Is there a w ay to add cells to the rows dynamically ?

    ReplyDelete
  6. // Loop through the rows in the Table and insert data from the data source.
    for (int row = 1; row < invoice_table.RowCount; row++)
    {
    for (int cell = 0; cell < invoice_table.Rows[row].Cells.Count; cell++)
    {
    Paragraph cell_paragraph = invoice_table.Rows[row].Cells[cell].Paragraphs[0];
    cell_paragraph.InsertText(data.Rows[row - 1].ItemArray[cell].ToString(), false);
    }
    }

    ReplyDelete
  7. Hi

    How can we add points with bullets and numbers?

    ReplyDelete
  8. Is there any way to find a specific table in an existing document and to add rows to it?

    ReplyDelete
  9. is there any way to merge columns ?

    ReplyDelete
  10. For instance Cheap D3 Gold, if you're a leading man in the Sixtieth level, but also in any section regarding Twentieth level GW2 Gold, the sport dynamically lowers your figures in order to main character Twenty first degree (most within + A single).

    ReplyDelete
  11. Have you created a table with "colspan" or "rowspan"?

    ReplyDelete
  12. My IDE (VS2010) is having trouble recognizing the First() function after Paragraphs.

    I have an insert but no inserttext or first. Anything I might be doing wrong?

    ReplyDelete
  13. How ca I insert table in specific position or insted of text

    ReplyDelete
  14. hey cathals... thanks for the library it help us here! if you have some spare time... please visit our place here in Asia, Indonesia >> Bandung city

    www.fgroupindonesia.com

    ReplyDelete
  15. This is a great example! Thanks! It doesn't look like the text is horizontally aligned in your picture like your code says it should be. I am having the same issue with my code :(

    ReplyDelete
  16. Hi,

    Nice examples.

    I want to pick a text box from an ms word document (2013) and convert it to an image using C#. How can i go about that?

    ReplyDelete
  17. Cool simple library, but i'm missing the feature to AppendTable in a table/cell

    ReplyDelete
  18. How to set vertical orientation for text in table?

    ReplyDelete
  19. How to add Numbered List inside Table Cell ?

    ReplyDelete
  20. Nice article..

    Can we check whether there is col span in table using docx package?

    ReplyDelete
  21. Hi, when I insert an image into a table cell and save the document, it becomes corrupted, and if you try to open it it shows the error message : uncpecified error location part /word/header2.xml
    however the file can be opened after recovery.

    how to avoid this error message ? this error happens whenever you insert an image. Otherwise everything is ok with the file. Any clues to the solution would be highly appreciated. Thanks.

    ReplyDelete
    Replies
    1. Hi,

      I have the same problem. Has the issue been solved?

      Kind Regards

      Delete
    2. Hi! Did You find solution for this issue?

      Delete
  22. How to add table in a numbered list. Is this library still maintained?

    ReplyDelete
  23. how I can add table at specific bookmark ?

    ReplyDelete
    Replies
    1. Did you solved that problem? I have the same question!

      Delete
    2. Try this:
      var tableBookmark = document.Bookmarks.FirstOrDefault(b => b.Name == "tableBookmark");
      var newTable = tableBookmark.Paragraph.InsertTableAfterSelf(5,5);

      Delete
  24. Hi, would it be possible to post a simple example that demonstrates creating a table of contents?

    thanks for the great component

    ReplyDelete
  25. Hi, would it be possible to post a simple example that demonstrates creating a table of contents?

    thanks for the great component

    ReplyDelete
  26. Hi Cathal,

    I am using DocX for formatting an existing word document. It was working fine until I got a requirement of coloring bullet. It colors text of the bullet but I have to color the bullet itself. Is there any provision in your library to do this.

    Thanks,
    Atul

    ReplyDelete
  27. Hi, you are a life saver, i had been looking for something like this for a while

    ReplyDelete
  28. How to add header on each page while printing table ?

    ReplyDelete
  29. Hello. How do I protect a table cell so the user cannot edit it? Thank you.

    ReplyDelete
  30. Hi, thanks for wonderful library. I am working on convert html to .docx. How would I set full width table in header?

    ReplyDelete
  31. Hi, thanks for wonderful library. I am working on convert html to .docx. How would I set full width table in header?

    ReplyDelete
  32. This comment has been removed by the author.

    ReplyDelete
  33. Can the table be positioned in a specific place on the page similar to the way ReplaceText works. I am building the table fine but it is not dropping into the template correctly.

    ReplyDelete
  34. Hi,
    Can I get the font family of a paragraph?
    I tried:
    var f = doc.Paragraphs[0].MagicText[0].formatting.FontFamily;
    but I get : Name = error CS0103: the name 'name' does not exist in the current context, and I get back the default "Tahoma" - in all cases.
    Thanks!
    Naomi

    ReplyDelete
  35. Hi,

    I would like to populate the table dynamically from a C# DataTable. Could you provide me an example.

    ReplyDelete
  36. Hello, thank you for you excellent library. I'am missing the function to vertically center text/grafic in an table cell. Is anybody close enough to the code to add this? thanks a lot in andvance

    ReplyDelete
  37. really great !!!!!!!!!!!!
    thank you soo much !!!!!!!!!!!!!!

    ReplyDelete
  38. Hi, how i can insert a table into a table's cell? Using this topTable.Rows[0].Cells[1].InsertTable(counterTable); i got an error opening the document. Thanks

    ReplyDelete
    Replies
    1. I found the solution. After the insert table into the cell, add a paragraph like this topTable.Rows[0].Cells[1].InsertParagraph(document.InsertParagraph(""));

      Delete
  39. Hello, I want to update TOC of word document after I processed on document and replaced data in template and saved as new document at different place. I am done with all other processing but how can I update the 'Table of Content' by using DocX library. Is there any auto update method exist for the same.

    ReplyDelete
  40. Hi,
    I have a table with 5 columns but table.InsertRow() keeps creating the row with only 3 cells. How can I prevent this?
    Thanks.

    ReplyDelete
    Replies
    1. This comment has been removed by the author.

      Delete
  41. Hi,
    I want to add a BackgroundColor to Cell, how can I do it? Can you tell me an example, please? Thanks.

    ReplyDelete
    Replies
    1. It's quite easy to do:

      Novacode.Table t = document.AddTable(3, 5);
      t.Rows[0].Cells[0].FillColor = Color.LightGray;

      Delete
  42. Hi, I have a problem with the width of the columns, when I insert text into the cell, change the width of the column, I used these codes, but the problem continues, is there other way?

    float[] colums = new float[] { 40, 150, 150, 300 };
    tWhatsapp.SetWidths(colums);

    tWhatsapp.Rows[i].Cells[2].Width = 150;

    ReplyDelete
    Replies
    1. I've never got SetWidths to work correctly either. Here's how I set my column sizes by explicitly setting the column width to each cell in the table:

      Novacode.Table t = document.AddTable(rows,columns);
      t.AutoFit = Novacode.AutoFit.ColumnWidth;
      for (int x = 0; x < t.ColumnCount; x++)
      {
      //t.SetColumnWidth(x, columnsizes[x]);
      for (int y = 0; y < t.RowCount; y++)
      {
      t.Rows[y].Cells[x].Width = columnsizes[x];
      }
      }

      Delete
    2. Very good! Thank you for your help

      Delete
  43. Hi Excellent library, I am using it to convert xml to doc (250 pages). I'm just struggling with SetTableCellMargin, it does not seem to have any effect (I tried values from 0.5 to 50, not knowing the unit it must use). Do I miss something?

    Table tab = doc.AddTable(5, 4);
    tab.SetWidthsPercentage(new float[] { 25, 45, 10, 20 }, doc.PageWidth - doc.MarginLeft - doc.MarginRight);
    tab.SetTableCellMargin(TableCellMarginType.bottom, 50);
    tab.SetTableCellMargin(TableCellMarginType.top, 50);

    ReplyDelete
  44. Hi the library is really helpful but I am stuck while adding a table inside a parent table cell . My documents as a nested table structure

    i am doing it as
    maintable.Rows[0].Cells[0].InsertTable(childtbale).Alignment = Alignment.center;

    but when I open the document it show the message "the document cannot be opened because there are problem with contents "

    Thanks In advance

    ReplyDelete
    Replies
    1. yes..even i am facing the same issue. how can we achieve table within a table using this lib.

      Delete
  45. Hello, is there any way to set the font size for the whole table or for specific cells?

    ReplyDelete
    Replies
    1. Here is some code I use to create a document table from a c# DataTable setting column sizes, header colour and font. You should be able to adapt this code for your own purposes


      private Novacode.Table AddTableToWord(Novacode.DocX document, DataTable table, double[] columnsizes, double fontsize)
      {
      Novacode.Table t = document.InsertTable(table.Rows.Count + 1, table.Columns.Count);
      // Set the column sizes
      t.AutoFit = Novacode.AutoFit.ColumnWidth;
      for (int x = 0; x < t.ColumnCount; x++)
      {
      //t.SetColumnWidth(x, columnsizes[x]);
      for (int y = 0; y < t.RowCount; y++)
      {
      t.Rows[y].Cells[x].Width = columnsizes[x] * 37.8; // Centimeter to Word conversion
      if (y > 0)
      t.Rows[y].Cells[x].VerticalAlignment = Novacode.VerticalAlignment.Top;
      else
      t.Rows[y].Cells[x].VerticalAlignment = Novacode.VerticalAlignment.Center; // Header is centered
      }
      }

      // Write the header
      for (int x = 0; x < t.ColumnCount; x++)
      {
      t.Rows[0].Cells[x].Paragraphs.First().Append(table.Columns[x].ColumnName).Font(new FontFamily("Arial")).FontSize(fontsize).Color(Color.FromArgb(89, 119, 134)).Bold().Alignment = Novacode.Alignment.left;
      t.Rows[0].Cells[x].FillColor = Color.LightGray;
      }

      int pos = 1;
      foreach (DataRow r in table.Rows)
      {
      for (int x = 0; x < t.ColumnCount; x++)
      {
      t.Rows[pos].Cells[x].Paragraphs.First().Append(r[x].ToString()).Font(new FontFamily("Arial")).FontSize(fontsize).Color(Color.Black).Alignment = Novacode.Alignment.left;
      }
      pos++;
      }
      t.Rows[0].TableHeader = true;

      return t;
      }

      Delete
  46. FYI: I had to change the font part to: ....Font("Arial").....

    I was originally running program in Visual Studio 2015, using DocX.1.0.0.22 - and no problems with ...FontFamily(new FontFamily("Arial"))....

    I moved software to Visual Studio 2019, and am using the latest DocX (DocXCore.1.0.4). I got a string conversion error. Now, it works with just ...Font("Arial")...

    ReplyDelete
  47. Hey Guys use this online converter for file converting;

    File Spinner

    ReplyDelete
  48. That spinner will helps you to transfer you one file to other formats;

    Odg to Pdf

    Mkv to Mp3

    Mp4 to Swf

    Ogv to Zip

    Docx to Zip

    ReplyDelete
  49. Hi there, You have done an excellent post on DOCX - HTML Converter. I’ll certainly digg it and personally recommend to my friends.

    ReplyDelete
  50. Play Emperor Casino Games Online | Shootercasino
    Experience 제왕카지노 the feeling of Emperor Casino at Shootercasino. We 메리트카지노 provide online games like 카지노사이트 blackjack, baccarat, roulette, scratch cards and so much more!

    ReplyDelete