Question

I am trying to create word documents using Microsoft office interops. The document should contain a picture and some table content below. But when i add the content it doesn't get added the way I require.

I have provided the sample code below.

MSWord.Application oWordApp;
MSWord.Document oWordDoc;
oWordApp = new MSWord.Application();
oWordApp.Visible = true;
oWordApp.WindowState = MSWord.WdWindowState.wdWindowStateMinimize;
oWordDoc = oWordApp.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);

object start = 0;
object end = 0;

Microsoft.Office.Interop.Word.Range oRange = oWordDoc.Range(ref start,ref end);

oWordDoc.InlineShapes.AddPicture(imagepath, ref oMissing, ref oMissing, oRange);

Microsoft.Office.Interop.Word.Table tbl = oWordDoc.Tables.Add(oRange, 10, 2, ref oMissing, ref oMissing);
Random rnd = new Random();
for (int i = 0; i < 10; i++)
{
    tbl.Rows[i + 1].Cells[1].Range.Text = "Item#";
    tbl.Rows[i + 1].Cells[2].Range.Text = "Sample";
}

oWordDoc.SaveAs(svd.FileName, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                            ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                            ref oMissing, ref oMissing, ref oMissing, ref oMissing);
Was it helpful?

Solution

Have you tried mail merge? This way you can have a word template set and you can position your images and table just like you want. Then you only have to worry about merging your input fields with the template. And this way you can have multiple templates for different word documents if required. Here's an example:

Sending text to Mail-Merge Fields in Microsoft Word 2010

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top