c# - 根据表格单元格在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;
请帮助我提前谢谢。
解决方案
我已通过在表格中使用特定文本(占位符)来识别占位符并在该位置插入图像来解决此问题
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++;
}
}
}
}
}
推荐阅读
- php - 如何检查在 PHP 中提交的表单
- c++ - C++ If/Else 语句被跳过
- python - 当映射不是一对一时,ctypes 如何将 C 结构成员映射到 Python 类_fields_?
- reactjs - 似乎无法使用 Expo 的 Font.loadAsync 加载自定义字体
- spring - 使用spring cloud gateway路由grpc流量
- html - 如何将 a 标签的文本移动到导航栏的中间
- python-3.x - 在 Python gtk mate applet 中,PC 不活动 10 分钟后 GTK ToolButton 文本停止显示
- node.js - 如何使用 webpack 打包节点程序
- c# - 通过未分配(未知)组件访问协程
- c# - 如何获取发送到 azure IoT hub c# 的设备总数和消息总数