poi操作word文档(替换,插入图片)
2017-09-26 13:43
621 查看
前段时间项目上要用到一个替换word中的字符以及插入图片并导出的功能,google了一番发现别人的代码跑起来多多少少有些问题,所以就自己照着poi的api写了一个工具类,在此记录下来,如果有需要的朋友可以参考下:
CustomXWPFDocument.java
以下是源码
WordUtil.javapackage com.upsoft.util; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.net.URLEncoder; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.poi.POIXMLDocument; import org.apache.poi.hwpf.HWPFDocument; import org.apache.poi.hwpf.usermodel.Range; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.openxml4j.opc.OPCPackage; import org.apache.poi.xwpf.usermodel.XWPFParagraph; import org.apache.poi.xwpf.usermodel.XWPFRun; import org.apache.poi.xwpf.usermodel.XWPFTable; import org.apache.poi.xwpf.usermodel.XWPFTableCell; import org.apache.poi.xwpf.usermodel.XWPFTableRow; /** * Word工具类(带导出) * 依赖外部jar :poi version 3.9 * 支持 word 2003+ * @author liyuzhuang * */ public class WordUtil { public static String tempFilePath = "../tempFile/word/"; public static void main(String[] args) throws Exception{ Map<String, Object> param = new HashMap<String, Object>(); Map<String,Object> header = new HashMap<String, Object>(); header.put("width", 100); header.put("height", 50); header.put("type", "jpg"); header.put("content", "f:\\test\\head.jpg"); param.put("${12}$",header); param.put("${1}$", "左侧段落"); param.put("${2}$", "text"); param.put("${3}$", "such"); param.put("${4}$", "男"); param.put("${5}$", "2017/08/04"); param.put("${6}$", "头像.jpg"); param.put("${7}$", "14584df545656"); param.put("${8}$", "36°"); param.put("${9}$", "28mol"); param.put("${10}$", "36mol"); param.put("${11}$", "78g"); param.put("${date}$", "2018"); String result = replaceAndGenerateWord("f:\\test\\pH值分析原始记录.docx", param, "pH值分析原始记录333.docx", null, null); } /** * 替换word中的自定义字符串以及图片(适用于word2003+ 版本) * * 注:2003版本word不支持替换图片,2007版本以上可以替换图片 * * @param filePath * @param param * @param fileName * @param request * @param response * @return */ public static String replaceAndGenerateWord(String filePath, Map<String, Object> param, String fileName, HttpServletRequest request, HttpServletResponse response){ String[] sp = filePath.split("\\."); //判断文件是否有后缀名 if(sp.length > 0){ try{ //处理docx文档 2007-2013 if(sp[sp.length - 1].equalsIgnoreCase("docx")){ CustomXWPFDocument document = null; OPCPackage pack = POIXMLDocument.openPackage(filePath); document = new CustomXWPFDocument(pack); if (param != null && param.size() > 0) { //处理段落 List<XWPFParagraph> paragraphList = document.getParagraphs(); processParagraphs(paragraphList, param, document); //处理表格 Iterator<XWPFTable> it = document.getTablesIterator(); while (it.hasNext()) { XWPFTable table = it.next(); List<XWPFTableRow> rows = table.getRows(); for (XWPFTableRow row : rows) { List<XWPFTableCell> cells = row.getTableCells(); for (XWPFTableCell cell : cells) { List<XWPFParagraph> paragraphListTable = cell.getParagraphs(); processParagraphs(paragraphListTable, param, document); } } } createDir(tempFilePath); FileOutputStream fos = new FileOutputStream(new File(tempFilePath.concat(fileName))); document.write(fos); fos.flush(); fos.close(); doExport(fileName, tempFilePath.concat(fileName), request, response); return tempFilePath.concat(fileName); } //处理doc文档 97-2003 }else if(sp[sp.length - 1].equalsIgnoreCase("doc")){ HWPFDocument document = null; document = new HWPFDocument(new FileInputStream(filePath)); Range range = document.getRange(); for (Map.Entry<String, Object> entry : param.entrySet()) { Object value = entry.getValue(); if(value instanceof String){ range.replaceText(entry.getKey(), entry.getValue().toString()); }else if(value instanceof Map){ //TODO word2003暂时不能处理图片 } } createDir(tempFilePath); FileOutputStream fos = new FileOutputStream(new File(tempFilePath.concat(fileName))); document.write(fos); fos.flush(); fos.close(); doExport(fileName, tempFilePath.concat(fileName), request, response); return tempFilePath.concat(fileName); } }catch(Exception e){ return "fail"; } }else{ return "fail"; } return "success"; } /** * 处理段落 * @param paragraphList * @throws FileNotFoundException * @throws InvalidFormatException */ public static void processParagraphs(List<XWPFParagraph> paragraphList,Map<String, Object> param,CustomXWPFDocument doc) throws InvalidFormatException, FileNotFoundException{ if(paragraphList != null && paragraphList.size() > 0){ //首选循环段落 for(XWPFParagraph paragraph:paragraphList){ //获取段落的text boolean needDel = false; String text = paragraph.getText(); if(text != null){ for (Entry<String, Object> entry : param.entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); //替换 if(value instanceof String){ String text2 = text.replace(key, value.toString()); if(!text2.equals(text)){ needDel = true; } text = text2; }else if(value instanceof Map){ if(text.indexOf(key) != -1){ //特殊处理图片 int length = paragraph.getRuns().size(); //将原有的Run去掉 if (length > 0) { for (int i = (length - 1); i >= 0; i--) { paragraph.removeRun(i); } } String imgurl = (String)((Map<?, ?>) value).get("content"); String type = (String)((Map<?, ?>) value).get("type"); int width = (Integer) ((Map<?, ?>) value).get("width"); int height = (Integer) ((Map<?, ?>) value).get("height"); String blipId = doc.addPictureData(new FileInputStream(new File(imgurl)), getPictureType(type)); doc.createPicture(blipId,doc.getNextPicNameNumber(getPictureType(type)), width, height,paragraph); } } } } int length = paragraph.getRuns().size(); //将原有的Run去掉(原因是paragraph将XWPFRun分割成了一个乱七八糟的数组,例:${1}$,这个获取出来的是[$,{,1,},$],不能满足我们替换的要求,这里进行特殊处理) if(needDel){ if (length > 0) { for (int i = (length - 1); i >= 0; i--) { paragraph.removeRun(i); } //在段落里面插入我们替换过后的文本 XWPFRun newRun = paragraph.insertNewRun(0); newRun.setText(text, 0); paragraph.addRun(newRun); } } } } } /** * 根据图片类型,取得对应的图片类型代码 * @param picType * @return int */ private static int getPictureType(String picType){ int res = CustomXWPFDocument.PICTURE_TYPE_PICT; if(picType != null){ if(picType.equalsIgnoreCase("png")){ res = CustomXWPFDocument.PICTURE_TYPE_PNG; }else if(picType.equalsIgnoreCase("dib")){ res = CustomXWPFDocument.PICTURE_TYPE_DIB; }else if(picType.equalsIgnoreCase("emf")){ res = CustomXWPFDocument.PICTURE_TYPE_EMF; }else if(picType.equalsIgnoreCase("jpg") || picType.equalsIgnoreCase("jpeg")){ res = CustomXWPFDocument.PICTURE_TYPE_JPEG; }else if(picType.equalsIgnoreCase("wmf")){ res = CustomXWPFDocument.PICTURE_TYPE_WMF; } } return res; } /** * 导出 * * @param fileName * @param filePath * @param request * @param response */ public static void doExport(String fileName, String filePath, HttpServletRequest request, HttpServletResponse response){ BufferedInputStream bis = null; BufferedOutputStream bos = null; File file = null; // HttpServletResponse response = (HttpServletResponse)RpcContext.getContext().getResponse(HttpServletResponse.class); try { file = new File(filePath); // HttpServletRequest request = (HttpServletRequest)RpcContext.getContext().getRequest(HttpServletRequest.class); request.setCharacterEncoding("UTF-8"); String agent = request.getHeader("User-Agent").toUpperCase(); if ((agent.indexOf("MSIE") > 0) || ((agent.indexOf("RV") != -1) && (agent.indexOf("FIREFOX") == -1))) fileName = URLEncoder.encode(fileName, "UTF-8"); else { fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1"); } response.setContentType("application/x-msdownload;"); response.setHeader("Content-disposition", "attachment; filename=" + fileName); response.setHeader("Content-Length", String.valueOf(file.length())); bis = new BufferedInputStream(new FileInputStream(file)); bos = new BufferedOutputStream(response.getOutputStream()); byte[] buff = new byte[2048]; int bytesRead; while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) bos.write(buff, 0, bytesRead); } catch (Exception e) { // System.out.println("导出文件失败!"); } finally { try { if (bis != null) { bis.close(); } if (bos != null) { bos.close(); } file.delete(); } catch (Exception e) { // LOGGER.error("导出文件关闭流出错!", e); } } } /** * 创建目录 * @param basePath */ public static void createDir(String basePath) { File file = new File(basePath); if (!file.exists()) file.mkdirs(); } }
CustomXWPFDocument.java
package com.upsoft.util; import org.apache.poi.openxml4j.opc.OPCPackage; import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFParagraph; import org.apache.xmlbeans.XmlException; import org.apache.xmlbeans.XmlToken; import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualDrawingProps; import org.openxmlformats.schemas.drawingml.x2006.main.CTPositiveSize2D; import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTInline; import java.io.IOException; import java.io.InputStream; /** * 支持word2007+ 插入图片 * @author liyuzhuang * */ public class CustomXWPFDocument extends XWPFDocument { public CustomXWPFDocument(InputStream in) throws IOException { super(in); } public CustomXWPFDocument(OPCPackage pkg) throws IOException { super(pkg); } public void createPicture(String blipId,int id, int width, int height, XWPFParagraph paragraph) { final int EMU = 9525; width *= EMU; height *= EMU; //String blipId = getAllPictures().get(id).getPackageRelationship().getId(); // CTInline inline = createParagraph().createRun().getCTR().addNewDrawing().addNewInline(); //给段落插入图片 CTInline inline = paragraph.createRun().getCTR().addNewDrawing().addNewInline(); String picXml = "" + "<a:graphic xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\">" + " <a:graphicData uri=\"http://schemas.openxmlformats.org/drawingml/2006/picture\">" + " <pic:pic xmlns:pic=\"http://schemas.openxmlformats.org/drawingml/2006/picture\">" + " <pic:nvPicPr>" + " <pic:cNvPr id=\"" + id + "\" name=\"Generated\"/>" + " <pic:cNvPicPr/>" + " </pic:nvPicPr>" + " <pic:blipFill>" + " <a:blip r:embed=\"" + blipId + "\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\"/>" + " <a:stretch>" + " <a:fillRect/>" + " </a:stretch>" + " </pic:blipFill>" + " <pic:spPr>" + " <a:xfrm>" + " <a:off x=\"0\" y=\"0\"/>" + " <a:ext cx=\"" + width + "\" cy=\"" + height + "\"/>" + " </a:xfrm>" + " <a:prstGeom prst=\"rect\">" + " <a:avLst/>" + " </a:prstGeom>" + " </pic:spPr>" + " </pic:pic>" + " </a:graphicData>" + "</a:graphic>"; //CTGraphicalObjectData graphicData = inline.addNewGraphic().addNewGraphicData(); XmlToken xmlToken = null; try { xmlToken = XmlToken.Factory.parse(picXml); } catch(XmlException xe) { xe.printStackTrace(); } inline.set(xmlToken); //graphicData.set(xmlToken); inline.setDistT(0); inline.setDistB(0); inline.setDistL(0); inline.setDistR(0); CTPositiveSize2D extent = inline.addNewExtent(); extent.setCx(width); extent.setCy(height); CTNonVisualDrawingProps docPr = inline.addNewDocPr(); docPr.setId(id); docPr.setName("Picture " + id); docPr.setDescr("Generated"); } }
相关文章推荐
- java/poi读取word,并替换word中的文本内容,向word中插入图片的操作
- java/poi读取word,并替换word中的文本内容,向word中插入图片的操作
- poi操作word文档,以07版本为参考,将word文档中图片替换为文本(替换文本也一样),读图片可选文字内容
- POI操作Excel文档-插入图片
- delphi操作word基类,插入表格,分页符,日期,页码,替换,图片
- 【Java工具类】 POI操作word文档模版可修改文字图片
- poi生成word文档,插入图片,echar报表生成到word,word表格
- C# VS2012操作word文档 (二).插入表格图片
- c#调用Aspose.Word组件操作word 插入文字/图片/表格 书签替换套打
- delphi操作word基类,插入表格,分页符,日期,页码,替换,图片
- c#调用Aspose.Word组件操作word 插入文字/图片/表格 书签替换套打
- C#操作Word(五)——在Word文档中插入图片
- Java 替换word文档文字并指定位置插入图片
- 用C#操作office组件库实现word文档的创建及文字 表格 图片的插入
- C# 操作Word书签(二)——插入图片、表格到书签;读取、替换书签
- java poi组件 读取word文档 替换文档 内容 图片
- 利用POI操作不同版本word文档中的图片以及创建word文档
- 黄聪:C# web word文档操作,任意指定位置插入图片,表格简单操作
- 利用POI操作不同版本号word文档中的图片以及创建word文档
- 使用POI操作PPT文档(插入文本、图片)转