Word 2007文件, 替换书签内容

10 篇文章 0 订阅

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;


import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;


import org.springframework.util.Assert;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;


public final class Word2007Util {


public static void replaceBookMarks(File word2007File, File outFile,
   Map<String, String> bookMarkValues) throws IOException,
   ZipException, SAXException, ParserConfigurationException,
   TransformerException, TransformerConfigurationException {
  Assert.notNull(word2007File);
  Assert.isTrue(word2007File.exists(), "file not exist");
  Assert.isTrue(word2007File.canRead(), "file can't be read");
  Assert.isTrue(word2007File.canWrite(), "file can't be wrote");
  ZipFile docxFile = null;
  ZipOutputStream docxOutFile = null;
  try{
   docxFile = new ZipFile(word2007File);
   ZipEntry documentXML = docxFile.getEntry("word/document.xml");
   InputStream documentXMLIS = docxFile.getInputStream(documentXML);
   DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
   Document doc = dbf.newDocumentBuilder().parse(documentXMLIS);
   NodeList bookmarks = doc.getElementsByTagName("w:bookmarkStart");
   for (int j = 0; j < bookmarks.getLength(); j++) {
    Element bookMarkStart = (Element) bookmarks.item(j); // 获取每个书签
    String bookMarkName = bookMarkStart.getAttribute("w:name"); // 书签名
    if(bookMarkValues.containsKey(bookMarkName)){
     // 书签处值开始
     Node wr = doc.createElement("w:r");
     Node wt = doc.createElement("w:t");
     Node wt_text = doc.createTextNode(bookMarkValues.get(bookMarkName));
     wt.appendChild(wt_text);
     wr.appendChild(wt);
     // 书签处值结束
     Element node = (Element) bookMarkStart.getNextSibling();
     NodeList wtList = node.getElementsByTagName("w:t");
     if (wtList.getLength() == 0) {
      bookMarkStart.appendChild(wr);
     } else {
      Element wtNode = (Element) wtList.item(0);
      wtNode.setTextContent(bookMarkValues.get(bookMarkName));
     }
    }
   }
   Transformer t = TransformerFactory.newInstance().newTransformer();
   ByteArrayOutputStream baos = new ByteArrayOutputStream();
   t.transform(new DOMSource(doc), new StreamResult(baos));
   docxOutFile = new ZipOutputStream(new FileOutputStream(outFile));
   @SuppressWarnings("unchecked")
   Enumeration<ZipEntry> entriesIter = (Enumeration<ZipEntry>) docxFile.entries();
   while (entriesIter.hasMoreElements()) {
    ZipEntry entry = null;
    entry = entriesIter.nextElement();
    if (entry.getName().equals("word/document.xml")) {
     byte[] data = baos.toByteArray();
     docxOutFile.putNextEntry(new ZipEntry(entry.getName()));
     docxOutFile.write(data, 0, data.length);
     docxOutFile.closeEntry();
    } else {
     InputStream incoming = docxFile.getInputStream(entry);
     int size = 1024;
     byte[] data = new byte[size];
     long totalSize = entry.getSize();
     int n = (int)(totalSize / size);
     int m = (int)(totalSize % size);
     docxOutFile.putNextEntry(new ZipEntry(entry.getName()));
     for(int i = 0; i < n; i++){
      int readCount = incoming.read(data, 0, size);
      docxOutFile.write(data, 0, readCount);
     }
     if(m > 0){
      int readCount = incoming.read(data, 0, m);
      docxOutFile.write(data, 0, readCount);
     }
     docxOutFile.closeEntry();
    }
   }
  } finally {
   if(docxFile != null){
    docxFile.close();
   }
   if(docxOutFile != null){
    docxOutFile.close();
   }
  }
 }

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
首先当然是定义word模板,在需要替换的地方加上标签。 菜单-插入-书签,输入属性名,如year,date,pic1,voList等等。 打印页面: 需要把打印的数据从后台取出,以单个vo(一个对象)为一组,或以voList(对象的列表集合)为一组 组织好页面上 再得到这些数据后进行替换。 数据组织形式如下: <div id="export2word"> <form id="singleVo" name="singleVo"> <textarea name="jcxcrs" style="display:none"><c:out value="${zywstjfxbgVO.jcxcrs }"/></textarea> <textarea name="xcjhl" style="display:none"><c:out value="${zywstjfxbgVO.xcjhl }"/></textarea> <textarea name="tbjcxcrs" style="display:none"><c:out value="${tbjcxcrs }"/></textarea> <textarea name="tptest" style="display:none">../zwgl/zw008-ZwMkjbxxCTRL-showWxytp.png?xh=3041</textarea> </form> <c:forEach var="mxvo" items="${jgList}" varStatus="s"> <form name="mxvoForm"> <!-- 注:这里的宽度设置为表格单元格宽度(厘米*100)--> <textarea name="tbjcmcrs" style="width:349;display:none"><c:out value="${mxvo.tbjcmcrs }"/></textarea> <textarea name="tbjcmcrsbl" style="width:270;display:none"><c:out value="${mxvo.tbjcmcrsbl }"/></textarea> <textarea name="tbjcxcrs" style="width:477;display:none"><c:out value="${mxvo.tbjcxcrs}"/></textarea> <textarea name="tbjcxcrsbl" style="display:none"><c:out value="${mxvo.tbjcxcrsbl }"/></textarea> </form> </c:forEach> </div> 使用: <input type="button" id="select2" name="select2" class="button" value="导出数据" onclick="print2doc();"> <script type="text/javascript" src="../public/scripts/export2word.js"></script> <script type="text/javascript"> function print2doc(){ //参数为模板(与页面的相对)路径 var word = new WordApp("test.doc"); //参数为form名,vo中需要添加的属性(为空时form里所有属性) var vo = word.getSingleVo("singleVo",["jcxcrs","xcjhl","tbjcxcrs"]); //var vo = word.getSingleVo("singleVo"); //组织成的图片vo var tpvo = word.getSingleVo("singleVo",["tptest"]); //参数为 form名,需要添加的属性(顺序为生成表格列的顺序,为空时form里的所有属性和顺序) var voList = word.getVoList("mxvoForm",["tbjcmcrs","tbjcmcrsbl","tbjczsrs"]); //var voList = word.getVoList("mxvoForm"); //替换普通书签 word.replaceBookmarkUsevo(vo); //替换图片书签 word.replaceBookmarkUsepicvo(tpvo); //替换书签jgList,画出表格形成多行数据。 word.replaceBookmarkUsevolist("jgList",voList); //文档可见 word.wordObj.visible=true; //word.closeApp(); } </script> 注意: 替换图片的值需要解释一下: 1.可以设为相对本页面的路径如../zbgl/abc.png 2.如果是输出流,则需要把请求输出流的url映射成以图片格式结尾的。如/.../abc.do?id=123换成/../abc.png?id=123 可以在web.xml里配一个servlet,如以*.png的请求转成.do的。如: public class PngDispatcherServlet extends HttpServlet { private static final long serialVersionUID = 6230740581031996144L; public void init() throws ServletException { } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //StringBuffer url = request.getRequestURL(); StringBuffer url = new StringBuffer(request.getRequestURI()); if(request.getQueryString() != null) { url.append('?'); url.append(request.getQueryString()); } String newUrl = url.toString().replaceAll(".png", ".do"); ServletContext sc = getServletContext(); RequestDispatcher rd = sc.getRequestDispatcher(newUrl); //定向的页面 rd.forward(request, response); } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值