I have to built C# application that clone data from one word file to another using Microsoft.Office.Interop.Word but when i'm try to read table from one file and write it into another i must use Table.Add() it contains Range, Number of Rows and Number of Columns. source word file contains dynamic table structure like first row contains 7 cells, second contains 3 cell, third row contains 4 cells and so on. it is possible to create single row table with dynamic column but is it possible to create in single table with dynamic rows as well dynamic column?
2 Answers
You are correct that when you use Table.Add, Word always creates a table with a uniform number of rows and columns. There isn't an alternative API that lets you specify an irregular structure, so if you use Add you basically have to copy the row/column/cell structure, item by item.
But because you are starting with a table in Word (not in Excel) you can use the FormattedText property of the source and destination ranges to make a copy of the entire table with cell structure and text, without using the clipboard/copy/paste.
For example, if you want to copy the first table from your original document to the beginning of your copy document, you can do something like this:
Word.Application wordApp = new Application();
wordApp.Visible = true;
Word.Document originaldoc = wordApp.Documents.Open("c:\\test\\original.docx", false);
Word.Document copydoc = wordApp.Documents.Open("c:\\test\\copy.docx", false);
copydoc.Range(0, 0).FormattedText = originaldoc.Tables[1].Range.FormattedText;
Here i'm posting my own question solution. i was find some way and this answer is also helpful for me to achieve the solution.
here i'm just read original document table's cell and convert text using function and assign it to copied document.
Application wordApp = new Application();
object CopiedDocumentObject = @"D:\CopiedDocumentFile.docx";
int CopiedDocRowCounter = 1;
Document OriginalDocument = wordApp.Documents.Open("D:\\OriginaldocumentFile.docx", 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);
Document CopiedDocument = wordApp.Documents.Add(ref missing, ref missing, ref missing);
CopiedDocument.Range(0, 0).FormattedText = OriginalDocument.Tables[1].Range.FormattedText;
foreach (Row tableRow in OriginalDocument.Tables[1].Rows)
{
for (int cellCounter = 1; cellCounter <= tableRow.Cells.Count; cellCounter++)
{
//Convert string and assign it to new document's table cell
CopiedDocument.Tables[1].Rows[CopiedDocRowCounter].Cells[cellCounter].Range.Text = UnicodeText(tableRow.Cells[cellCounter].Range.Text);
}
CopiedDocRowCounter++;
}
CopiedDocument.SaveAs2(ref CopiedDocumentObject);
OriginalDocument.Close();
CopiedDocument.Close();
wordApp.Quit();