private void InsertWordPic(string filepath,string picCode,string picWidth,string picheight) { StreamWriter sw; string tmpfile=Path.GetTempPath+ "//new123.xml "; bool isNewFlag=false; //检查文件是否存在,否,则创建一个 if(!File.Exists(filepath)) { File.Create(tmpfile).Close(); isNewFlag=true; } else { File.Copy(filepath,Path.GetTempPath+ "//new123.xml ",true); } string context= " "; //如果是新文件 if(isNewFlag) { //写入WORD xml文件头 context= " <?xml version=/ "1.0/ " encoding=/ "UTF-8/ " standalone=/ "yes/ "?> <?mso-application progid=/ "Word.Document/ "?> <w:wordDocument xmlns:w=/ "http://schemas.microsoft.com/office/word/2003/wordml/ " mlns:v=/ "urn:schemas-microsoft-com:vml/ " xmlns:w10=/ "urn:schemas-microsoft-com:office:word/ " xmlns:sl=/ "http://emas.microsoft.com/schemaLibrary/2003/core/ " xmlns:aml=/ "http://schemas.microsoft.com/aml/2001/core/ " xmlns:wx=/ "http://schemas.microsoft.com/office/word/2003/auxHint/ " xmlns:o=/ "urn:schemas-microsoft-com:office:office/ " ns:dt=/ "uuid:C2F41010-65B3-11d1-A29F-00AA00C14882/ " w:macrosPresent=/ "no/ " w:embeddedObjPresent=/ "no/ " w:xPresent=/ "no/ " xml:space=/ "preserve/ "> <w:body> "; //写入图片数据编码,类似XML数据岛 context=string.Concat(context, " <w:pict> <w:binData w:name=/ "wordml://01000001.gif/ "> ",picCode, " </w:binData> "); //写入图片显示定义 string PicName=(new FileInfo(filepath)).Name; context=string.Concat(context, " <v:shape id=/ "_x0000_i1025/ " type=/ "#_x0000_t75/ " style="/" mce_style="/" "width: "+picWidth+ ";height: "+picheight+ "/ "> <v:imagedata src="/" mce_src="/" "wordml://01000001.gif/ " o:title=/ " "+PicName.Substring(0,PicName.LastIndexOf( ". "))+ "/ "/> </v:shape> </w:pict> "); //关闭文档结构 context=string.Concat(context, " </w:wordDocument> "); //打开文件,准备写入 sw=new StreamWriter(tmpfile); sw.Write(context); sw.Flush(); sw.Close(); } else { //准备 //写入图片数据编码,类似XML数据岛。w:binData可以在文档的如何地方,w:name是KEY context=string.Concat(context, " <w:binData w:name=/ "wordml://01000001.gif/ "> ",picCode, " </w:binData> "); //打开临时文件,插入图片数据 XmlDocument doc=new XmlDocument(tmpfile); XmlDocumentFragment df=doc.CreateDocumentFragment(); df.InnerXml=context; XmlNode node=doc.DocumentElement; node.InsertAfter(df,node.LastChild); //写入图片显示定义 string PicName=(new FileInfo(filepath)).Name; context=string.Concat( " <w:pict> <v:shape id=/ "_x0000_i1025/ " type=/ "#_x0000_t75/ " style="/" mce_style="/" "width: "+picWidth+ ";height: "+picheight+ "/ "> <v:imagedata src="/" mce_src="/" "wordml://01000001.gif/ " o:title=/ " "+PicName.Substring(0,PicName.LastIndexOf( ". "))+ "/ "/> </v:shape> </w:pict> "); df.InnerXml=context; //查找要显示图片的节点 插入 大概的写一下肯定有错误,要用XPATH定义精确比较快! foreach(XmlNode nd in (node.SelectNodes( "w:pict "))) { if(nd.InnerText== "这里插入图片 ") { nd.InsertAfter(df,node.FirstChild); } } doc.Save(); } //返回文档 File.Copy(tmpfile,filepath,true); }