首页 > 解决方案 > 根据表格单元格在word文档中动态插入图片

问题描述

我正在将图像添加到它正在工作的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;

请帮助我提前谢谢。

标签: c#imagems-wordoffice-interop

解决方案


我已通过在表格中使用特定文本(占位符)来识别占位符并在该位置插入图像来解决此问题

            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++;
                            }                                    
                        }

                    }
                }
            }

推荐阅读