我正在将图像添加到正在运行的Word文档中,但是我的主要问题如下:
1)在特定单元格中的表格的Word文档中插入图像。
2)如果word文档中有很多表,并且我想在某些特定的表中插入,该怎么办?
我正在使用Microsoft.Office.Interop.Word dll对word进行操作。在代码中我已经创建了一个静态表,如何实现动态?
我的代码如下:
Microsoft.Office.Interop.Word.Document doc = app.Documents.Open(ref wordfilename, 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);
Range rngPic = doc.Tables[1].Cell(1, 3).Range;
// we can even select a particular cell in the table
//Range rngPic = rng.Tables[1].Cell(2, 3).Range;
string logoLocation = ConfigurationManager.AppSettings["LogoLocation"];
var LogoPath = Path.Combine((HttpContext.Current.Server.MapPath(logoLocation)), fpnInfo.LogoPath);
Microsoft.Office.Interop.Word.InlineShape picture = rngPic.InlineShapes.AddPicture(LogoPath, Type.Missing, Type.Missing, Type.Missing);
picture.Height = 50;
picture.Width = 50;
请提前帮助我。
答案 0 :(得分:0)
我已通过使用表格中的特定文本(占位符)来解决此问题,以识别占位符并在该位置插入图片
foreach (Microsoft.Office.Interop.Word.Table tb in doc.Tables)
{
int imageCounter = 0;
for (int row = 1; row <= tb.Rows.Count; row++)
{
for (int Cols = 1; Cols <= tb.Columns.Count; Cols++)
{
var tableCell = tb.Cell(row, Cols);
var cellText = tableCell.Range.Text;
if (cellText.Contains("Image1"))
{
tableCell.Range.Text = "";
if (fpnImage != null && fpnImage.Any() && fpnImage[imageCounter].Path != null)
{
var MediaPathImage1 = Path.Combine((HttpContext.Current.Server.MapPath(mediaImage)), fpnImage[imageCounter].Path);
var rangePic = tb.Cell(row, Cols).Range;
Microsoft.Office.Interop.Word.InlineShape rangePicture = rangePic.InlineShapes.AddPicture(MediaPathImage1, Type.Missing, Type.Missing, Type.Missing);
rangePicture.Height = imageHeight;
rangePicture.Width = imageWidth;
imageCounter++;
}
}
}
}
}