poi 3.6


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletResponse;

import java.util.Set;

import org.apache.poi.POIXMLDocument;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
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;

/**
 * 
 * @author User
 * @see{poi}
 * @base  poi Version-3.7.0
 */
public class RenderDocx {

	 public static XWPFDocument changWord(String inputUrl, Map<String, Object> textMap) {;
	 XWPFDocument document = null;
     try {
         //获取docx解析对象
         document = new XWPFDocument(POIXMLDocument.openPackage(inputUrl));
         //解析替换文本段落对象
          renderText(document, textMap);
         //解析替换表格对象
          renderTable(document, textMap);
     } catch (IOException e) {
         e.printStackTrace();
     }
     return document;
 }

	private static void renderTable(XWPFDocument document, Map<String, Object> textMap) {
		 //获取表格对象集合
        List<XWPFTable> tables = document.getTables();
        
     
        	 //循环所有需要进行替换的文本,进行替换
            for (int i = 0; i < tables.size(); i++) {
                XWPFTable table = tables.get(i);
                if(checkText(table.getText())){
                    List<XWPFTableRow> rows = table.getRows();
                    //遍历表格,并替换模板
                    eachTable(document,rows, textMap);
                }
            }
		
	}

	private static void eachTable(XWPFDocument document, List<XWPFTableRow> rows, Map<String, Object> textMap) {
		 for (XWPFTableRow row : rows) {
	            List<XWPFTableCell> cells = row.getTableCells();
	            for (XWPFTableCell cell : cells) {
	                //判断单元格是否需要替换
	                if(checkText(cell.getText())){
	                    List<XWPFParagraph> paragraphs = cell.getParagraphs();
	                    for (XWPFParagraph paragraph : paragraphs) {
	                        List<XWPFRun> runs = paragraph.getRuns();
	                        for (XWPFRun run : runs) {
	                            Object ob = changeValue(run.toString(), textMap);
	                            if (ob instanceof String || ob instanceof Long || ob instanceof BigDecimal || ob instanceof Double  || ob instanceof Integer){
	                                run.setText(ob.toString(),0);
	                            } 
	                        }
	                    }
	                }
	            }
	        }
	}

	private static void renderText(XWPFDocument document, Map<String, Object> textMap) {
		 //获取段落集合
        List<XWPFParagraph> paragraphs = document.getParagraphs();
        for (XWPFParagraph paragraph : paragraphs) {
            //判断此段落时候需要进行替换
            String text = paragraph.getText();
 
            if(checkText(text)){
                List<XWPFRun> runs = paragraph.getRuns();
                for (XWPFRun run : runs) {
                    //替换模板原来位置
                	if(run.toString().contains("$") ||  run.toString().contains("{") || run.toString().contains("}")){
                		Object ob = changeValue(run.toString(), textMap);
                        if (ob instanceof String || ob instanceof Long || ob instanceof BigDecimal || ob instanceof Double  || ob instanceof Integer){
                            run.setText(ob.toString(),0);
                        }
                	}
                    
                }
            }
        }
	}
	
 /**
     * 匹配传入信息集合与模板
     * @param value 模板需要替换的区域
     * @param textMap 传入信息集合
     * @return 模板需要替换区域信息集合对应值
     */
	private static Object changeValue(String value, Map<String, Object> textMap) {
		Set<Entry<String, Object>> textSets = textMap.entrySet();
        Object valu = "";
        for (Entry<String, Object> textSet : textSets) {
            //匹配模板与替换值 格式${key}
            String key = textSet.getKey();
            if(value.indexOf(key)!= -1){
                valu = textSet.getValue();
            }
        }
        return valu;
	}

	/**
     * 判断文本中时候包含$
     * @param text 文本
     * @return 包含返回true,不包含返回false
     */
	private static boolean checkText(String text) {
	  
	    
	        boolean check  =  false;
	        if(text.indexOf("$")!= -1){
	            check = true;
	        }
	        return check;
	     
	}
	
	
	public static void main(String[] args) {
//		String path = request.getSession().getServletContext().getRealPath("/");
//		String inputUrl = path + File.separator + "template" + File.separator + "abcd.docx";
//		String downloadUrl = path + File.separator + "download" + File.separator + "abcd.docx";
 
//		Map<String, Object> dmap = aaaService.queryData(id);
//		CustomXWPFDocument doc = changWord(inputUrl, dmap  );
//		FileOutputStream fopts = new FileOutputStream(downloadUrl);
//		doc.write(fopts);
//		fopts.close();
//		downloadFile(downloadUrl, response, "下载文件.docx");
	}
	
	/**
	 * @see 配套删除
	 * @param fileUrl
	 * @param response
	 * @param name
	 */
	public void downloadFile(String fileUrl, HttpServletResponse response, String name) {
		OutputStream out = null;
		InputStream inputStream = null;
		try {
			// 得到输入流  
			File file = new File(fileUrl);
			inputStream = new FileInputStream(file);
			response.reset();
			response.setContentType("application/octet-stream; charset=utf-8");
			response.setHeader("Content-Disposition",
					"attachment; filename=" + new String(name.getBytes("GBK"), "ISO8859_1"));
			// 获取响应报文输出流对象  
			// 获取response对象的输出流
			out = response.getOutputStream();
			byte[] buffer = new byte[1024];
			int len;
			// 循环取出流中的数据
			while ((len = inputStream.read(buffer)) != -1) {
				out.write(buffer, 0, len);
			}
			// 然后删除该文件
			file.delete();
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage());
		} finally {
			try {
				inputStream.close();
				out.close();
			} catch (IOException e) {
				throw new RuntimeException(e.getMessage());
			}
		}
	}
}