最近公司要做一套OA系统,涉及到word文档模版操作,第一时间想到的是office com组件,以前使用过,但是这个组件有个问题要求系统必须安装office完整系统,同时属于单利模式,不能同时占用office应用程序,考虑到用户现实情况,决定探索新方法,经过百度和一老哥的指点,发现OpenXML成了不二之选。OpenXML利用office文档生成原理(word,excel,ppt实际上都是XML格式),开始各种查,初学者可以参考https://docs.microsoft.com/zh-cn/office/open-xml/open-xml-sdk,最后完美解决需求,可以在word模版中的任意位置写入各类字符,颇有成就感(最起码不用花钱买那些插件),等领导给客户介绍完系统后,客户也接受,当然也会提需求,这都没事,最让人蛋疼的是 客户发现自己的业务有20多个模版,好吧,加班加点的加书签,做呗。。。这还远远不够,我最担心的事情发生了,需求里面有插入图片信息,赶紧查sdk,有写入图片,太好了,赶紧引入,fk,不能在指定位置写入,时间好紧,查百度,也没查出个毛毛雨,只能硬着头皮去看文档,一遍遍的试,功夫不负有心人,第二天的凌晨2点 ,实现了 哈哈。。。。
废话说多了 直接 上代码
///
/// 根据书签位置插入图片信息
///
/// 书签
/// 图片路径
public void InsertAPicture(string fileName, string document, string bookmark)
{
OpenSettings openSettings = new OpenSettings();
// Add the MarkupCompatibilityProcessSettings
openSettings.MarkupCompatibilityProcessSettings =
new MarkupCompatibilityProcessSettings(
MarkupCompatibilityProcessMode.ProcessAllParts,
FileFormatVersions.Office2007);
// string document = @"E:\**项目\**文书\108.docx";
// document = @"F:\Project_Code\SVNProject\SDHS_SZCG_ZCCG\SZZF\SZZFWord\xcjckyyszj.docx";
using (WordprocessingDocument wordprocessingDocument =
WordprocessingDocument.Open(document, true))
{
MainDocumentPart mainPart = wordprocessingDocument.MainDocumentPart;
ImagePart imagePart = mainPart.AddImagePart(ImagePartType.Jpeg);
using (FileStream stream = new FileStream(fileName, FileMode.Open))
{
imagePart.FeedData(stream);
}
AddImageToBody(wordprocessingDocument, mainPart.GetIdOfPart(imagePart));
}
}
//帮助文档中的源码,直接拷贝出来修改,根据
private static void AddImageToBody(WordprocessingDocument wordDoc, string relationshipId)
{
// Define the reference of the image.
var element =
new Drawing(
new DW.Inline(
new DW.Extent() { Cx = 1990000L, Cy = 1792000L },
new DW.EffectExtent()
{
LeftEdge = 0L,
TopEdge = 0L,
RightEdge = 0L,
BottomEdge = 0L
},
new DW.DocProperties()
{
Id = (UInt32Value)1U,
Name = "Picture 1"
},
new DW.NonVisualGraphicFrameDrawingProperties(
new A.GraphicFrameLocks() { NoChangeAspect = true }),
new A.Graphic(
new A.GraphicData(
new PIC.Picture(
new PIC.NonVisualPictureProperties(
new PIC.NonVisualDrawingProperties()
{
Id = (UInt32Value)0U,
Name = "New Bitmap Image.jpg"
},
new PIC.NonVisualPictureDrawingProperties()),
new PIC.BlipFill(
new A.Blip(
new A.BlipExtensionList(
new A.BlipExtension()
{
Uri =
"{28A0092B-C50C-407E-A947-70E740481C1C}"
})
)
{
Embed = relationshipId,
CompressionState =
A.BlipCompressionValues.Print
},
new A.Stretch(
new A.FillRectangle())),
new PIC.ShapeProperties(
new A.Transform2D(
new A.Offset() { X = 0L, Y = 0L },
new A.Extents() { Cx = 1990000L, Cy = 1792000L }),
new A.PresetGeometry(
new A.AdjustValueList()
) { Preset = A.ShapeTypeValues.Rectangle }))
) { Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture" })
)
{
DistanceFromTop = (UInt32Value)0U,
DistanceFromBottom = (UInt32Value)0U,
DistanceFromLeft = (UInt32Value)0U,
DistanceFromRight = (UInt32Value)0U,
// EditId = "50D07946"
});
//书签处写入---这是关键 tp为传递过来的 书签名称,替换成变量即可
MainDocumentPart mainPart = wordDoc.MainDocumentPart;
var bookmarks = from bm in mainPart.Document.Body.Descendants<BookmarkStart>()
where bm.Name == "tp"
select bm;
var bookmark = bookmarks.SingleOrDefault();
if (bookmark != null)
{
OpenXmlElement elem = bookmark.NextSibling();
while (elem != null && !(elem is BookmarkEnd))
{
OpenXmlElement nextElem = elem.NextSibling();
elem.Remove();
elem = nextElem;
}
var parent = bookmark.Parent; // bookmark's parent element
Run run = new Run(new RunProperties());
//该处插入element,注意区分和字符插入的方法Append(dd)
parent.InsertAfter<Run>(new Run(new Run(element)), bookmark);
}
}
直接copy就可使用