-1

I have a word document in which there is table added. I want to access that document and add new blank row to the table which is already in it. I referred this reference link and created below code:

static void Main(string[] args)
{
    string filePath = "C:\\TestDoc1.docx";
    byte[] byteArray = File.ReadAllBytes(filePath);

    using (MemoryStream stream = new MemoryStream())
    {
        stream.Write(byteArray, 0, (int)byteArray.Length);

        using (WordprocessingDocument doc = WordprocessingDocument.Open(stream, true))
        {
            Body bod = doc.MainDocumentPart.Document.Body;
            foreach (Table t in bod.Descendants<Table>().Where(tbl => tbl.GetFirstChild<TableRow>().Descendants<TableCell>().Count() == 4))
            {
                // Create a row.
                TableRow tr = new TableRow();
                t.Append(tr);
            }

        }
        // Save the file with the new name
        File.WriteAllBytes("C:\\TestDoc2.docx", stream.ToArray());
    }
} 

However, code does not throw any error. But when I open TestDoc2.docx I am getting the below error:

enter image description here

What am I missing?

Community
  • 1
  • 1
Mohemmad K
  • 809
  • 7
  • 33
  • 74

2 Answers2

0

I found a code plex helper dll which is fast, lightweight and it does not require Microsoft Word or Office to be installed. You can get that from here. Add reference of this dll to your solution and write below code:

using(DocX doc = DocX.Load(filePath))
{
    // you can use whatever condition you would like to select the table from that table.
   // I am using the Title field value in the Table Properties wizard under Alter Text tab 
    Novacode.Table t = doc.Tables.Cast<Table>().FirstOrDefault(tbl => tbl.TableCaption == "Test");
    Row r = t.InsertRow();
    doc.SaveAs("C:\\TestDoc2.docx");
}

It works like a charm in my case!!! :-)

Hope this helps others too.

Mohemmad K
  • 809
  • 7
  • 33
  • 74
0

What was missing in your first code was a TableCell and a Paragraph

// Create a row.
TableRow tr = new TableRow(new TableCell(new Paragraph()));
t.Append(tr);

A TableRow must at least contain one TableCell and a TableCell must contain a Paragraph

Maxime Porté
  • 1,034
  • 8
  • 13