How to insert an image to cell in Word Table

Word表へのコードでの画像貼り付け VSTO
Word表へのコードでの画像貼り付け
スポンサーリンク

In Word, via VSTO (C#), We’ve been not know how to insert an image to a cell of table.

Below code, you can insert an image to cell of Word’s table. Before add the header “using Microsoft.Office.Interop.Word; ” to your code.

  
Application app = Globals.ThisAddIn.Application;  

// Select inserting point. 
Range tableLocation  = app.ActiveDocument.Range(0, 0);  

// Insert a table. 
Table newTable = app.ActiveDocument.Tables.Add(tableLocation, 3, 4);  
newTable.Borders.InsideLineStyle = WdLineStyle.wdLineStyleSingle;
newTable.Borders.OutsideLineStyle = WdLineStyle.wdLineStyleSingle;

// Set row's height. 
newTable.Rows.Height = 50;  

// Select Cell1 and add text. 
Cell cell1 = app.ActiveDocument.Tables[1].Cell(1, 1);   
cell1.Range.Text = "Name1-1";   
cell1.Range.ParagraphFormat.Alignment 
  = WdParagraphAlignment.wdAlignParagraphLeft;  

// Insert Image to Cell1 (*** HERE IS IMPORTANT ***) 
cell1.Range.InlineShapes.AddPicture(@"C:\tmp\img.png");   

// Select Cell1 and add text. 
Cell cell2 = app.ActiveDocument.Tables[1].Cell(2, 2);   
cell2.Range.Text = "Name2-2";   
cell2.Range.ParagraphFormat.Alignment       
 =  WdParagraphAlignment.wdAlignParagraphLeft;   

// Insert Image to Cell2 (*** HERE IS IMPORTANT ***)  
cell2.Range.InlineShapes.AddPicture(@"C:\tmp\img.png");  

This code’s result is bellow!! It’s very useful.

タイトルとURLをコピーしました