今天学习了在world指定标签插入文字或者图片
第一步:
先给模板文档添加标签(设置如下)
文字标签
图片标签
两种都是位置标签,因为后面我们要在这个位置上插入。如果要给同一类进行插入一样的东西的话,就可以使用名称做为标签符号。
第二步:
在指定标签处插入文本。
public void InsertTextToWorld()
{
object Nothing = System.Reflection.Missing.Value;
Microsoft.Office.Interop.Word.Application worldApp = new Microsoft.Office.Interop.Word.Application();
object filename = @"E:\PR\Functions\InsertToWorld\InsertToWorld\InsertToWorld\bin\Debug\Template\不动产登记申请书.docx";//模板地址
//定义插入图片是否随word文档一起保存
object saveWithDocument = true;
//打开word文档
Microsoft.Office.Interop.Word.Document doc = worldApp.Documents.Open(ref filename, ref Nothing, ref Nothing, ref Nothing,
ref Nothing, ref Nothing, ref Nothing, ref Nothing,
ref Nothing, ref Nothing, ref Nothing, ref Nothing,
ref Nothing, ref Nothing, ref Nothing, ref Nothing);
object BookMarkXH = "Year";
if (worldApp.ActiveDocument.Bookmarks.Exists("Year"))
{
worldApp.ActiveDocument.Bookmarks.get_Item(ref BookMarkXH).Select();
doc.Bookmarks.get_Item(ref BookMarkXH).Range.Text = "2019";
}
try
{
doc.SaveAs2(@"E:\PR\Functions\InsertToWorld\data\data1.docx");//保存的地址
doc.Saved = false;
doc.Close(ref Nothing, ref Nothing, ref Nothing);
}
catch
{
throw;
}
}
在指定标签位置处插入图片。
public void InsertPictureToWorld()
{
object Nothing = System.Reflection.Missing.Value;
Microsoft.Office.Interop.Word.Application worldApp = new Microsoft.Office.Interop.Word.Application();
object filename= @"E:\PR\Functions\InsertToWorld\InsertToWorld\InsertToWorld\bin\Debug\Template\不动产权籍调查表.docx";
//定义该插入图片是否为外部链接
object linkToFile = true;
//定义插入图片是否随word文档一起保存
object saveWithDocument = true;
//打开word文档
Microsoft.Office.Interop.Word.Document doc = worldApp.Documents.Open(ref filename, ref Nothing, ref Nothing, ref Nothing,
ref Nothing, ref Nothing, ref Nothing, ref Nothing,
ref Nothing, ref Nothing, ref Nothing, ref Nothing,
ref Nothing, ref Nothing, ref Nothing, ref Nothing);
try
{
//标签
object bookMark = "testPicture";
//图片
string replacePic = @"C:\Users\JR04\Desktop\Pic.jpg";
if (doc.Bookmarks.Exists(Convert.ToString(bookMark)) == true)
{
//查找书签
doc.Bookmarks.get_Item(ref bookMark).Select();
//设置图片位置
worldApp.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
//在书签的位置添加图片
InlineShape inlineShape = worldApp.Selection.InlineShapes.AddPicture(replacePic, ref linkToFile, ref saveWithDocument, ref Nothing);
//设置图片大小
inlineShape.Width =200;
inlineShape.Height = 200;
doc.SaveAs2(@"E:\PR\Functions\InsertToWorld\data\data2.docx");
doc.Close(ref Nothing, ref Nothing, ref Nothing);
}
else
{
//word文档中不存在该书签,关闭文档
doc.Close(ref Nothing, ref Nothing, ref Nothing);
}
}
catch
{
}
}
结果展示: