注意: 

 

  • doc文件的读取,需要导入poi-scratchpad包:
  • docx文件读取,需要导入poi-ooxml包:

一、引入pom

<dependency>
		    <groupId>org.apache.poi</groupId>
			<artifactId>poi</artifactId>
			<version>3.10.1</version>
		</dependency>
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi-scratchpad</artifactId>
			<version>3.10.1</version>
		</dependency>
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi-ooxml</artifactId>
			<version>3.10.1</version>
		</dependency>
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi-ooxml-schemas</artifactId>
			<version>3.10.1</version>
		</dependency>

 二、新建一个docx文件作为模板,里面需要替换的部分用{xxx}标识出来

java poi更具标题获取 java poi word_List

三、接口内容如下:

/**
     * 生成简历
     *
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping(value = {"/down"}, method = {RequestMethod.GET, RequestMethod.POST})
    public void down(HttpServletResponse response, @CookieValue(SessionManager.SESSION_NAME) String sessionId) throws Exception {
        SysUser user = userSessionManager.getUser(sessionId);
        AdjustAbilityPerson bean = this.adjustAbilityPersonRepository.findByuser(user.getId());
        String path = templateDir;
        XWPFDocument xwpfDocument = this.downLoadFile(response, bean, path, user);//创建对象
        response.reset();
        response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("个人简历.docx", "UTF-8"));
        response.setContentType("application/octet-stream");
        OutputStream out = response.getOutputStream();
        xwpfDocument.write(out);//将word对象内容写入输出流
    }

三、上图中downLoadFile方法内容

public XWPFDocument downLoadFile(HttpServletResponse response, AdjustAbilityPerson bean, String filePath, SysUser user) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Map<String, String> map = new HashMap<String, String>();//把要替换的内容放入map
        filePath = filePath + "/" + "jianli.docx";//模板文件名称
        if (bean != null) {
            String str = "";
            map.put("{userName}", bean.getUserName() != null ? bean.getUserName() + "" : "");
            if (bean.getSex() != null && bean.getSex() == 0) {
                map.put("{sexName}", "男");
            } else if (bean.getSex() != null && bean.getSex() == 1) {
                map.put("{sexName}", "女");
            } else {
                map.put("{sexName}", "");
            }
            //省略其他的替换……
        }
        OPCPackage pack = POIXMLDocument.openPackage(filePath);//打开word模板文件
        XWPFDocument document = new XWPFDocument(pack);//创建word对象
        CommonFileUtil.replaceStrs(document, map);//替换内容
        imagerList(document, pack,bean.getCreateuser().getId());//简历有图片,插入图片
        return document;
    }

 四、上图插入图片方法imagerList

private void imagerList(XWPFDocument document, OPCPackage pack, Long id) throws IOException {
        ImagerXWPFDocument doc = new ImagerXWPFDocument(pack);
        List<XWPFTable> ts = document.getTables();
        XWPFTable table = ts.get(0);
        int rowinx = 0;
        XWPFTableRow row = null;
        List<Affix> affixs1 = this.affixService.findAffixsByObjectId(5002, id + "");
        if (affixs1 != null && affixs1.size() > 0) {
            row = table.getRow(0);
            Map<String, Object> imager = new HashMap<String, Object>();
            imager.put("width", 115);
            imager.put("height", 180);
            String filePath = this.affixConfig.getBaseDir() + affixs1.get(0).getSource();
            if(!new File(filePath).exists()){
                return;
            }
            InputStream in = new FileInputStream(filePath);
            byte[] content = CommonFileUtil.inputStream2ByteArray(in, false);
            imager.put("content", content);
            imager.put("type", "");
            XWPFParagraph paragraph = null;
            XWPFTableCell cell = row.getCell(4);
            List<XWPFParagraph> paragraphs = cell.getParagraphs();
            paragraph = paragraphs.get(0);
            CommonFileUtil.replaceImgager(paragraph, imager, doc);
        }
    }

五、CommonFileUtil工具类包括替换内容,插入图片、文件复制等功能

package cn.com.maxtech.huatai.util;

import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.log4j.Logger;
import org.apache.poi.xwpf.usermodel.ParagraphAlignment;
import org.apache.poi.xwpf.usermodel.TextAlignment;
import org.apache.poi.xwpf.usermodel.UnderlinePatterns;
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;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTBorder;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblBorders;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTcPr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STBorder;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STVerticalJc;
/** 
 * 公共文件类
 * */
public class CommonFileUtil {
	protected final static Logger log = Logger.getLogger(CommonFileUtil.class);
	/**
	 * 替换文档中的内容
	 * @param document 文档对象
	 * @param map 数据集合
	 * */
	public static void replaceStrs(XWPFDocument document,Map<String,String> map){
		replaceStrs(document, map,null);
	}
	/**
	 * 替换文档中的内容
	 * @param document 文档对象
	 * @param map 数据集合
	 * @param list 显示下划线的key集合
	 * */
	public static void replaceStrs(XWPFDocument document,Map<String,String> map,List<String> list){
		replaceParagraphStrs(document, map,list);
		replaceTableStrs(document, map,list);
	}
	/**
	 * 替换文档中的内容
	 * @param document 文档对象
	 * @param map 数据集合
	 * @param list 显示下划线的key集合
	 * @param removes 删除指定key所在的表格行的key集合
	 * */
	public static void replaceStrs(XWPFDocument document,Map<String,String> map,List<String> list,
			List<String> removes){
		replaceParagraphStrs(document, map,list);
		replaceTableStrs(document, map,list,null,null,removes);
	}
	/**
	 * 替换文档中的内容
	 * @param document 文档对象
	 * @param map 数据集合
	 * @param list 显示下划线的key集合
	 * @param breaks 多行显示的key集合
	 * @param separator 分隔符
	 * @param removes 删除指定key所在的表格行的key集合
	 * */
	public static void replaceStrs(XWPFDocument document,Map<String,String> map,List<String> list,
			List<String> breaks,String separator,List<String> removes){
		replaceParagraphStrs(document, map,list,breaks,separator);
		replaceTableStrs(document, map,list,breaks,separator,removes);
	}
	/**
	 * 替换段落中的内容
	 * @param document 文档对象
	 * @param map 数据集合
	 * */
	public static void replaceParagraphStrs(XWPFDocument document,Map<String,String> map){
		replaceParagraphStrs(document, map, null);
	}
	/**
	 * 替换段落中的内容
	 * @param document 文档对象
	 * @param map 数据集合
	 * @param list 显示下划线的key集合
	 * */
	public static void replaceParagraphStrs(XWPFDocument document,Map<String,String> map,List<String> list){
		replaceParagraphStrs(document, map, list,null,null);
	}
	
	/**
	 * 替换段落中的内容
	 * @param document 文档对象
	 * @param map 数据集合
	 * @param breaks 多行显示的key集合
	 * @param separator 分隔符
	 * */
	public static void replaceParagraphStrs(XWPFDocument document,Map<String,String> map,List<String> breaks,String separator){
		replaceParagraphStrs(document, map, null, breaks, separator,null);
	}
	
	/**
	 * 替换段落中的内容
	 * @param document 文档对象
	 * @param map 数据集合
	 * @param list 显示下划线的key集合
	 * @param breaks 多行显示的key集合
	 * @param separator 分隔符
	 * */
	public static void replaceParagraphStrs(XWPFDocument document,Map<String,String> map,List<String> list,
			List<String> breaks,String separator){
		replaceParagraphStrs(document, map, list, breaks, separator,null);
	}
	
	/**
	 * 替换段落中的内容
	 * @param document 文档对象
	 * @param map 数据集合
	 * @param list 显示下划线的key集合
	 * @param breaks 多行显示的key集合
	 * @param separator 分隔符
	 * @param replaceList 使用指定存在函数替换为key集合
	 * */
	public static void replaceParagraphStrs(XWPFDocument document,Map<String,String> map,List<String> list,
			List<String> breaks,String separator,List<String> replaceList){
		replaceParagraphStrs(document, map, list, breaks, separator, replaceList,null,null,null,null,null);
	}
	/**
	 * 替换段落中的内容
	 * @param document 文档对象
	 * @param map 数据集合
	 * @param list 显示下划线的key集合
	 * @param breaks 多行显示的key集合
	 * @param separator 分隔符
	 * @param replaceList 使用指定存在函数替换为key集合
	 * @param removeList 要删除标题的内容key集合
	 * */
	public static void replaceParagraphStrs(XWPFDocument document,Map<String,String> map,List<String> list,
			List<String> breaks,String separator,List<String> replaceList,List<String> removeList){
		replaceParagraphStrs(document, map, list, breaks, separator, replaceList,null,null,null,null,removeList);
	}
	
	/**
	 * 替换段落中的内容
	 * @param document 文档对象
	 * @param map 数据集合
	 * @param list 显示下划线的key集合
	 * @param breaks 多行显示的key集合
	 * @param separator 分隔符
	 * @param replaceList 使用指定存在函数替换为key集合
	 * @param fontFamily 字体
	 * @param fontSize 文字大小
	 * @param fontBold 是否加粗
	 * @param showLine 是否显示下划线
	 * @param removeList 要删除标题的内容key集合
	 * */
	public static void replaceParagraphStrs(XWPFDocument document,Map<String,String> map,List<String> list,
			List<String> breaks,String separator,List<String> replaceList,String fontFamily,Integer fontSize,
				Boolean fontBold,Boolean showLine,List<String> removeList){
		boolean removeTag=false;
		if(removeList!=null&&removeList.size()>0){
			removeTag=true;
		}
		boolean replaceTag=false;
		if(replaceList!=null&&replaceList.size()>0){
			replaceTag=true;
		}
		boolean flag=false;
		if(list!=null&&list.size()>0){
			flag=true;
		}
		boolean flags=false;
		if(breaks!=null&&breaks.size()>0&&separator!=null&&!"".equals(separator)){
			flags=true;
		}
		Iterator<XWPFParagraph> itPara = document.getParagraphsIterator();
		String mkey=null;
		String temp=null;
		Iterator<String> iterator = null;
		XWPFRun xwpfRun=null;
		while (itPara.hasNext()) {
			boolean tag=false;
              XWPFParagraph paragraph = (XWPFParagraph) itPara.next();
              iterator = map.keySet().iterator();
              while (iterator.hasNext()) {
            	  mkey = iterator.next();
                  List<XWPFRun> run=paragraph.getRuns();
                  for(int i=0;i<run.size();i++){
                	  xwpfRun=run.get(i);
                	  temp=xwpfRun.getText(xwpfRun.getTextPosition());
                      if(temp!=null ){
                    	  boolean tgs=false;
                    	  if(replaceTag&&replaceList.contains(mkey)){
            				  tgs=temp.trim().contains(mkey);
            			  }else{
            				  tgs=temp.trim().equals(mkey);
            			  }
                    	  if(tgs&&removeTag&&removeList.contains(mkey)){
                    		  xwpfRun.removeBreak();
                    		  continue;
                    	  }
                    	  if(tgs){
                    		  if(flag&&list.contains(mkey)){//设置下划线属性
                    			  xwpfRun.setUnderline(UnderlinePatterns.DOT_DOT_DASH);
                    		  }
                    		  if(flags&&breaks.contains(mkey)){
                    			  xwpfRun.setText("",0);  
                    			  tag=true;
                    			  break;
                    		  }else{
                    			  if(replaceTag&&replaceList.contains(mkey)){
                    				  xwpfRun.setText(replaceStrs(temp,map,replaceList),0); 
                    			  }else{
                    				  xwpfRun.setText(map.get(mkey)==null?"":map.get(mkey),0);    
                    			  }
                    			  if(fontFamily!=null&&!fontFamily.equals("")){
                    				  xwpfRun.setFontFamily("宋体");  
                         		  }
                         		  if(fontSize!=null){
                         			 xwpfRun.setFontSize(fontSize);
                         		  }
                         		  if(fontBold!=null&&fontBold){
                          			 xwpfRun.setBold(true);  
                          		  }
                         		  if(showLine!=null&&showLine){
                         			 xwpfRun.setUnderline(UnderlinePatterns.DOT_DOT_DASH);
                         		  }
                    		  }
                    	  }
                      }
                  }    
                  if(tag){
                	  tag=false;
                	  if(map.get(mkey)!=null){
                		  String[] sts=map.get(mkey).split(separator);
                		  if(sts.length>0){
                			  for (int j =0; j <= sts.length-1; j++) {
                				  XWPFRun run_s = paragraph.insertNewRun(paragraph.getRuns().size()-1); 
                				  run_s.setText(sts[j]); 
                				  if(j<sts.length-1){
                					  run_s.addBreak();
                				  }
                				  if(fontFamily!=null&&!fontFamily.equals("")){
                					  run_s.setFontFamily("宋体");  
                				  }
                				  if(fontSize!=null){
                					  run_s.setFontSize(fontSize);
                				  }
                				  if(fontBold!=null&&fontBold){
                					  xwpfRun.setBold(true);  
                				  }
                				  if(showLine!=null&&showLine){
                					  xwpfRun.setUnderline(UnderlinePatterns.DOT_DOT_DASH);
                				  }
                			  }
                		  }
                	  }
                  }
              } 
		}
	}
	
	private static String replaceStrs(String strs,Map<String,String> map,List<String> replaceList){
		String value="";
		String key="";
		for (int i = 0; i < replaceList.size(); i++) {
			key=replaceList.get(i);
			value=map.get(key);
			if(value!=null){
				strs=strs.replace(key, value);
			}
		}
		return strs;
	}

	/**
	 * 替换表格中内容
	 * @param document 文档对象
	 * @param map 数据集合
	 * */
	public static void replaceTableStrs(XWPFDocument document,Map<String,String> map){
		replaceTableStrs(document, map, null);
	}
	/**
	 * 替换表格中内容
	 * @param document 文档对象
	 * @param map 数据集合
	 * @param list 显示下划线的key集合
	 * */
	public static void replaceTableStrs(XWPFDocument document,Map<String,String> map,List<String> list){
		replaceTableStrs(document, map, list, null, null);
	}
	/**
	 * 替换表格中内容
	 * @param document 文档对象
	 * @param map 数据集合
	 * @param list 显示下划线的key集合
	 * @param breaks 多行显示的key集合
	 * @param separator 分隔符
	 * */
	public static void replaceTableStrs(XWPFDocument document,Map<String,String> map,List<String> list,
			List<String> breaks,String separator){
		replaceTableStrs(document, map, list, breaks, separator,null);
	}
	/**
	 * 替换表格中内容
	 * @param document 文档对象
	 * @param map 数据集合
	 * @param list 显示下划线的key集合
	 * @param breaks 多行显示的key集合
	 * @param separator 分隔符
	 * @param removes 删除指定key所在的表格行的key集合
	 * */
	public static void replaceTableStrs(XWPFDocument document,Map<String,String> map,List<String> list,
			List<String> breaks,String separator,List<String> removes){
		replaceTableStrs(document, map, list, breaks, separator, removes,null,null);
	}
	/**
	 * 替换表格中内容
	 * @param document 文档对象
	 * @param map 数据集合
	 * @param list 显示下划线的key集合
	 * @param breaks 多行显示的key集合
	 * @param separator 分隔符
	 * @param removes 删除指定key所在的表格行的key集合
	 * @param tableIndex 指定的表格索引
	 * @param isHidden 是否隐藏表格边框
	 * */
	public static void replaceTableStrs(XWPFDocument document,Map<String,String> map,List<String> list,
			List<String> breaks,String separator,List<String> removes,Integer tableIndex,Boolean isHidden){
		replaceTableStrs(document, map, list, breaks, separator, removes, tableIndex, isHidden,null);
	}
	
	/**
	 * 替换表格中内容
	 * @param document 文档对象
	 * @param map 数据集合
	 * @param list 显示下划线的key集合
	 * @param breaks 多行显示的key集合
	 * @param separator 分隔符
	 * @param removes 删除指定key所在的表格行的key集合
	 * @param tableIndex 指定的表格索引
	 * @param isHidden 是否隐藏表格边框
	 * @param boldList 要加粗的内容集合
	 * */
	public static void replaceTableStrs(XWPFDocument document,Map<String,String> map,List<String> list,
			List<String> breaks,String separator,List<String> removes,Integer tableIndex,Boolean isHidden,List<String> boldList){
		if(isHidden==null){
			isHidden=false;
		}
		boolean flag=false;
		if(list!=null&&list.size()>0){
			flag=true;
		}
		boolean flags=false;
		if(breaks!=null&&breaks.size()>0&&separator!=null&&!"".equals(separator)){
			flags=true;
		}
		removeTableRow(document, removes);
		if(tableIndex!=null){
			XWPFTable table=document.getTables().get(tableIndex);
			tableControl(table, map, list, breaks, separator, removes, tableIndex, isHidden, flag, flags,boldList);
		}else{
			Iterator<XWPFTable> itTable = document.getTablesIterator();
			while (itTable.hasNext()) {
				XWPFTable table = (XWPFTable) itTable.next();
				tableControl(table, map, list, breaks, separator, removes, tableIndex, isHidden, flag, flags,boldList);
			}
		}
		
	} 
	
	private static String getBoldStr(String strs,List<String> boldList){
		int count=boldList.size();
		for (int i = 0; i < count; i++) {
			if(strs.contains(boldList.get(i))){
				return boldList.get(i);
			}
		}
		return "";
	}
	
	private static void tableControl( XWPFTable table,Map<String,String> map,List<String> list,
			List<String> breaks,String separator,List<String> removes,Integer tableIndex,Boolean isHidden,
			boolean flag,boolean flags,List<String> boldList){
		boolean tagBold=false;
		if(boldList!=null&&boldList.size()>0){
			tagBold=true;
		}
		if(isHidden){
			controlTableBorder(table);
		}
		String mkey=null;
		String mvalue=null;
		String temp=null;
		XWPFRun xwpfRun=null;
		Iterator<String> iterator = null;
		int rcount = table.getNumberOfRows();
        for (int i = 0; i < rcount; i++) {
            XWPFTableRow row = table.getRow(i);
            List<XWPFTableCell> cells = row.getTableCells();
            for (XWPFTableCell cell : cells) {
            	temp=cell.getText();
            	iterator = map.keySet().iterator();
            	while (iterator.hasNext()) {
               	    mkey = iterator.next();
               	    mvalue=map.get(mkey);
               	    if(mvalue==null){
               	    	continue;
               	    }
                	String s=temp.replace(mkey, mvalue).replace(mkey, mvalue);
                	List<XWPFParagraph> paras=cell.getParagraphs();
                	if(paras.size()>0){
                		for (XWPFParagraph para : paras) { 
                			boolean tag=false;
//                			para.setAlignment(ParagraphAlignment.CENTER);
//                			para.setBorderBottom(Borders.DOUBLE);
//                			para.setBorderTop(Borders.DOUBLE);
//                			para.setBorderRight(Borders.DOUBLE);
//                			para.setBorderLeft(Borders.DOUBLE);
//                			para.setBorderBetween(Borders.SINGLE);
//                			para.setVerticalAlignment(TextAlignment.TOP);
                            List<XWPFRun> runs = para.getRuns();  
                   	         for (int k=0; k<runs.size(); k++) { 
                   	        	 xwpfRun=runs.get(k);
                            	 String ts=xwpfRun.getText(xwpfRun.getTextPosition());
                                  if(ts!=null && ts.trim().equals(mkey)){
                            		  if(flag&&list.contains(mkey)){//设置下划线属性
//                            			  xwpfRun.setUnderline(UnderlinePatterns.DOT_DOT_DASH);
                            			  xwpfRun.setUnderline(UnderlinePatterns.SINGLE);
                            		  }
                            		  if(flags&&breaks.contains(mkey)){
                            			  xwpfRun.setText("",0);  
                            			  tag=true;
                            			  break;
                            		  }else{
                            			  String tempValue=map.get(mkey);
                            			  if(tagBold){
                            				  String boldStr=getBoldStr(tempValue, boldList);
                            				  if(!boldStr.equals("")){
                            					  int a_1=tempValue.indexOf(boldStr);
                            					  String temps=tempValue.substring(a_1+boldStr.length());
                            					  xwpfRun.setBold(true); 
                            					  xwpfRun.setFontFamily("Times New Roman");
                            					  xwpfRun.setFontSize(10);
                            					  xwpfRun.setText(boldStr, 0);
                            					  XWPFRun xwpf=para.createRun();
                            					  xwpf.setText(temps, 0);
                            				  }else{
                            					  xwpfRun.setText(tempValue,0);    
                            				  }
                            			  }else{
                            				  xwpfRun.setText(tempValue,0);
                            			  }
                            		  }
                                  }
                   	         }
                   	         if(tag){
                   	        	tag=false;
                	        	 String[] sts=map.get(mkey).split(separator);
                	        	 for (int j =0; j <= sts.length-1; j++) {
                	        		 XWPFRun run = para.insertNewRun(para.getRuns().size()-1); 
//                	        		 run.setText(sts[j]); 
                	        		 String tempValue=sts[j];
	                       			  if(tagBold){
	                       				  String boldStr=getBoldStr(tempValue, boldList);
	                       				  if(!boldStr.equals("")){
	                       					  int a_1=tempValue.indexOf(boldStr);
	                       					  String temps=tempValue.substring(a_1+boldStr.length());
	                       					  run.setBold(true); 
	                       					  xwpfRun.setFontFamily("Times New Roman");
                        					  xwpfRun.setFontSize(10);
                        					  xwpfRun.setText(boldStr, 0);
	                       					 run.setText(boldStr);
	                       					run=para.insertNewRun(para.getRuns().size()-1); 
	                       					run.setText(temps);
	                       				  }else{
	                       					run.setText(tempValue);    
	                       				  }
	                       			  }else{
	                       				run.setText(tempValue);
	                       			  }
                	        		 
                	        		 if(j<sts.length-1){
                	        			 run.addBreak();
                	        		 }
                	        		 
//                     		 		 run.setFontFamily("宋体");  
//                     		 		 run.setBold(true);  
                	        	 }
                	         }
                        }  
                	}else{
                		cell.setText(s);
                	}
                }
            }
        }
	}
	
	public static void addParagraphOfTable(XWPFDocument document,Integer tableIndex,Integer rowIndex,Integer cellIndex,List<String> list,
			String fontFamily,Integer fontSize,Boolean bold){
		if(fontFamily==null||fontFamily.equals("")){
			fontFamily="宋体";
		}
		if(fontSize==null){
			fontSize=16;
		}
		if(bold==null){
			bold=true;
		}
		if(tableIndex==null){
			tableIndex=document.getTables().size()-1;
		}
		if(rowIndex==null){
			rowIndex=0;
		}
		if(cellIndex==null){
			cellIndex=0;
		}
		XWPFTable table=document.getTables().get(tableIndex);
		XWPFTableRow row=table.getRow(rowIndex);
		XWPFTableCell cell=row.getCell(cellIndex);
		addParagraphOfCell(cell, list,fontFamily,fontSize,bold);
	} 
	
	public static void addParagraphOfCell(XWPFTableCell cell,List<String> list,String fontFamily,Integer fontSize,Boolean bold){
		XWPFParagraph xwpf=null;
		if(list!=null&&list.size()>0){
			for (String string : list) {
				xwpf=cell.addParagraph();
				xwpf.setAlignment(ParagraphAlignment.CENTER);
				XWPFRun run=xwpf.createRun();
				run.setFontFamily(fontFamily);
				run.setFontSize(fontSize);
				run.setBold(bold);
				run.setText(string);
			}
		}
	}
	
	private static void controlTableBorder(XWPFTable ss){
		CTTblBorders borders=ss.getCTTbl().getTblPr().addNewTblBorders();
	    CTBorder hBorder=borders.addNewInsideH();
	    hBorder.setVal(STBorder.Enum.forString("none"));
	    hBorder.setSz(new BigInteger("1"));
	    hBorder.setColor("0000FF");
	    CTBorder vBorder=borders.addNewInsideV();
	    vBorder.setVal(STBorder.Enum.forString("none"));
	    vBorder.setSz(new BigInteger("1"));
	    vBorder.setColor("00FF00");
	    CTBorder lBorder=borders.addNewLeft();
	    lBorder.setVal(STBorder.Enum.forString("none"));
	    lBorder.setSz(new BigInteger("1"));
	    lBorder.setColor("3399FF");
	    CTBorder rBorder=borders.addNewRight();
	    rBorder.setVal(STBorder.Enum.forString("none"));
	    rBorder.setSz(new BigInteger("1"));
	    rBorder.setColor("F2B11F");
	    CTBorder tBorder=borders.addNewTop();
	    tBorder.setVal(STBorder.Enum.forString("none"));
	    tBorder.setSz(new BigInteger("1"));
	    tBorder.setColor("C3599D");
	    CTBorder bBorder=borders.addNewBottom();
	    bBorder.setVal(STBorder.Enum.forString("none"));
	    bBorder.setSz(new BigInteger("1"));
	    bBorder.setColor("F7E415");
	}
	
	/**
	 * 在指定表格中增加行
	 * @param document 文档对象
	 * @param tableIndex 表格索引
	 * @param rowIndex 行索引
	 * @param datas 行数据集合
	 * */
	public static void addTableRow(XWPFDocument document,int tableIndex,Integer rowIndex,List<List<String>> datas){
		addTableRow(document, tableIndex, rowIndex, datas,0);
	}
	/**
	 * 在指定表格中增加行
	 * @param document 文档对象
	 * @param tableIndex 表格索引
	 * @param rowIndex 行索引
	 * @param datas 行数据集合 
	 * @param getRowIndex 获取指定行的列数据
	 * */
	public static void addTableRow(XWPFDocument document,int tableIndex,Integer rowIndex,List<List<String>> datas,int getRowIndex){
		addTableRow(document, tableIndex, rowIndex, datas, getRowIndex, null,null,null,null);
	}
	/**
	 * 在指定表格中增加行
	 * @param document 文档对象
	 * @param tableIndex 表格索引
	 * @param rowIndex 行索引
	 * @param datas 行数据集合 
	 * @param getRowIndex 获取指定行的列数据
	 * @param align 布局方式
	 * @param num 次数
	 * @param fontFamily 字体
	 * @param fontSize 大小
	 * */
	public static void addTableRow(XWPFDocument document,int tableIndex,Integer rowIndex,List<List<String>> datas,
			int getRowIndex,String align,Integer num,String fontFamily,Integer fontSize){
		if(align==null){
			align="center";
		}
		boolean tag=false;
		if(num!=null){
			tag=true;
		}
		List<XWPFTable> ts=document.getTables();
		XWPFTable ss=ts.get(tableIndex);
	    int c1=datas.size();
	    List<String> list=null;
	    XWPFTableRow rw=null;
		for (int i = c1-1; i >=0; i--) {
			list=datas.get(i);
			if(rowIndex==null){
				rowIndex=ss.getRows().size();
			}
			XWPFTableRow rws=ss.getRow(getRowIndex);
			rw=ss.insertNewTableRow(rowIndex);
			List<XWPFTableCell> rss=rws.getTableCells();
			XWPFTableCell rs=null;
			BigInteger width=BigInteger.valueOf(20);
			for (int j = 0; j < rss.size(); j++) {
				width=rss.get(j).getCTTc().getTcPr().getTcW().getW();
				rs=rw.addNewTableCell();
				CTTcPr cellPr = rs.getCTTc().addNewTcPr();  
				cellPr.addNewVAlign().setVal(STVerticalJc.CENTER);  
				if(align.equals("center")){
				}else if(align.equals("left")){
					cellPr.addNewVAlign().setVal(STVerticalJc.TOP);
				}else if(align.equals("right")){
					cellPr.addNewVAlign().setVal(STVerticalJc.CENTER); 
				}
				//设置宽度  
				cellPr.addNewTcW().setW(width);  
				XWPFParagraph p=null;
				if(rs.getParagraphs().size()==0){
					p=rs.addParagraph();
				}else{
					p=rs.getParagraphs().get(0);
				}
				if(align.equals("center")){
					p.setAlignment(ParagraphAlignment.CENTER);
				}else if(align.equals("left")){
					p.setVerticalAlignment(TextAlignment.TOP);
					p.setAlignment(ParagraphAlignment.LEFT);  
				}else if(align.equals("right")){
					p.setAlignment(ParagraphAlignment.RIGHT);  
				}
				XWPFRun r= p.createRun();
				if(fontFamily!=null&&!"".equals(fontFamily)){
					r.setFontFamily(fontFamily);
				}
				if(fontSize!=null&&fontSize>0){
					r.setFontSize(fontSize);
				}
				if(!tag){
					r.setText(list.get(j));
				}
				if(tag){
					r.setText(list.get(j));
					for (int k = 0; k < num; k++) {
						r.addBreak();
					}
     	         }
			}
		}
	}
	
	public static void addChildTableOfTwoColumn(XWPFTable table,int row,int cell,Integer num,List<List<String>> datas){
		XWPFTableRow  xtrow=table.getRow(row);
		XWPFTableCell xtcell=xtrow.getCell(cell);
		XWPFTable ss=new XWPFTable(table.getCTTbl(), table.getBody());
		/***************************************/
		boolean tag=false;
		if(num!=null){
			tag=true;
		}
		String align="left";
	    int c1=datas.size();
	    List<String> list=null;
	    XWPFTableRow rw=null;
		for (int i = c1-1; i >=0; i--) {
			list=datas.get(i);
			XWPFTableRow rws=ss.getRow(0);
			rw=ss.insertNewTableRow(0);
			List<XWPFTableCell> rss=rws.getTableCells();
			XWPFTableCell rs=null;
			BigInteger width=BigInteger.valueOf(20);
			for (int j = 0; j < rss.size(); j++) {
				width=rss.get(j).getCTTc().getTcPr().getTcW().getW();
				rs=rw.addNewTableCell();
				CTTcPr cellPr = rs.getCTTc().addNewTcPr();  
				cellPr.addNewVAlign().setVal(STVerticalJc.CENTER);  
				if(align.equals("center")){
				}else if(align.equals("left")){
					cellPr.addNewVAlign().setVal(STVerticalJc.TOP);
				}else if(align.equals("right")){
					cellPr.addNewVAlign().setVal(STVerticalJc.CENTER); 
				}
				//设置宽度  
				cellPr.addNewTcW().setW(width);  
				XWPFParagraph p=null;
				if(rs.getParagraphs().size()==0){
					p=rs.addParagraph();
				}else{
					p=rs.getParagraphs().get(0);
				}
				if(align.equals("center")){
					p.setAlignment(ParagraphAlignment.CENTER);
				}else if(align.equals("left")){
					p.setVerticalAlignment(TextAlignment.TOP);
					p.setAlignment(ParagraphAlignment.LEFT);  
				}else if(align.equals("right")){
					p.setAlignment(ParagraphAlignment.RIGHT);  
				}
				XWPFRun r= p.createRun();
				if(!tag){
					r.setText(list.get(j));
				}
				if(tag){
					r.setText(list.get(j));
					for (int k = 0; k < num; k++) {
						r.addBreak();
					}
     	         }
			}
		}
		/*************************************/
		xtcell.insertTable(0, ss);
	}
	
	/**
	 * 删除表格行
	 * @param document 文档对象
	 * @param datas key集合(存在删除行中的key)
	 * */
	public static void removeTableRow(XWPFDocument document,List<String> list){
		if(list==null||list.size()==0){
			return;
		}
		String temp=null;
        Iterator<XWPFTable> itTable = document.getTablesIterator();
        Set<XWPFTableRow> rrows=null;
        while (itTable.hasNext()) {
        	boolean tag=false;
            XWPFTable table = (XWPFTable) itTable.next();
            int rcount = table.getNumberOfRows();
            rrows=new HashSet<XWPFTableRow>();
            for (int i = 0; i < rcount; i++) {
                XWPFTableRow row = table.getRow(i);
                List<XWPFTableCell> cells = row.getTableCells();
                for (XWPFTableCell cell : cells) {
                	temp=cell.getText();
                	for (String string : list) {
                		if(temp.contains(string)){
                			rrows.add(row);
                			tag=true;
                		}
					}
                }
            }
            if(tag){
            	iterationTable(table, rrows);
            }
        }
	} 
	private static void iterationTable(XWPFTable table,Set<XWPFTableRow> rows ){
		boolean tag=false;
		 int rcount = table.getNumberOfRows();
         for (int i = 0; i < rcount; i++) {
             XWPFTableRow row = table.getRow(i);
             for (XWPFTableRow xwpfTableRow : rows) {
            	 if(row.equals(xwpfTableRow)){
            		 table.removeRow(i);
            		 rows.remove(xwpfTableRow);
            		 tag=true;
            		 break;
            	 }
			}
            if(tag){
            	break;
            }
         }
         if(tag){
        	 iterationTable(table, rows);
         }
	}
	/**
	 * 在指定的table后追加行数据,一行一页
	 * @param document 文档对象
	 * @param tableIndex 表格索引
	 * @param datas 行数据集合
	 * */
	public static void appendTableRowOfPage(XWPFDocument document,int tableIndex,List<List<String>> datas){
		appendTableRowOfPage(document, tableIndex, datas,null);
	}
	/**
	 * 在指定的table后追加行数据,一行一页
	 * @param document 文档对象
	 * @param tableIndex 表格索引
	 * @param datas 行数据集合
	 * */
	public static void appendTableRowOfPage(XWPFDocument document,int tableIndex,List<List<String>> datas,List<List<PageDataStyle>> styles){
		Boolean tag=false;
		if(styles!=null&&styles.size()>0){
			tag=true;
		}
		
		List<XWPFTable> ts=document.getTables();
		XWPFTable ss=ts.get(tableIndex);
		CTTblBorders borders=ss.getCTTbl().getTblPr().addNewTblBorders();
	    CTBorder hBorder=borders.addNewInsideH();
	    hBorder.setVal(STBorder.Enum.forString("none"));
	    hBorder.setSz(new BigInteger("1"));
	    hBorder.setColor("0000FF");
	    CTBorder vBorder=borders.addNewInsideV();
	    vBorder.setVal(STBorder.Enum.forString("none"));
	    vBorder.setSz(new BigInteger("1"));
	    vBorder.setColor("00FF00");
	    CTBorder lBorder=borders.addNewLeft();
	    lBorder.setVal(STBorder.Enum.forString("none"));
	    lBorder.setSz(new BigInteger("1"));
	    lBorder.setColor("3399FF");
	    CTBorder rBorder=borders.addNewRight();
	    rBorder.setVal(STBorder.Enum.forString("none"));
	    rBorder.setSz(new BigInteger("1"));
	    rBorder.setColor("F2B11F");
	    CTBorder tBorder=borders.addNewTop();
	    tBorder.setVal(STBorder.Enum.forString("none"));
	    tBorder.setSz(new BigInteger("1"));
	    tBorder.setColor("C3599D");
	    CTBorder bBorder=borders.addNewBottom();
	    bBorder.setVal(STBorder.Enum.forString("none"));
	    bBorder.setSz(new BigInteger("1"));
	    bBorder.setColor("F7E415");
	    int c1=datas.size();
	    PageDataStyle style=null;
	    List<String> list=null;
	    List<PageDataStyle> pdss=null;
		for (int i = 0; i < c1; i++) {
			XWPFTableRow rw=ss.createRow();
			rw.setCantSplitRow(true);
			XWPFTableCell rs=rw.getCell(0);
			list=datas.get(i);
			int count=44-list.size();
			int size=list.size();
			List<XWPFParagraph> paras=rs.getParagraphs();
			if(tag){
				pdss=styles.get(i);
				XWPFParagraph txp=null;
				for (int j=0;j<=size-1;j++) {
					txp=rs.addParagraph();
					XWPFRun run =txp.insertNewRun(0);
					run.setText(list.get(j));  
					style=pdss.get(j);
					if(style.getBold()!=null){
						run.setBold(style.getBold());
					}
					if(style.getFamily()!=null){
						run.setFontFamily(style.getFamily());
					}
					if(style.getSize()!=null){
						run.setFontSize(style.getSize());
					}
					if(style.getAlign()==null||style.getAlign().equals("")){
						txp.setAlignment(ParagraphAlignment.LEFT);
					}else if(style.getAlign().equals("center")){
						txp.setAlignment(ParagraphAlignment.CENTER);
					}else if(style.getAlign().equals("left")){
						txp.setAlignment(ParagraphAlignment.LEFT);
					}else if(style.getAlign().equals("right")){
						txp.setAlignment(ParagraphAlignment.RIGHT);
					}
				}
				for (int j=0;j<count;j++) {
					rs.addParagraph();
				}
			}else{
				for (int j=0;j<count;j++) {
					XWPFRun run = paras.get(0).insertNewRun(0); 
					run.setText("");  
					run.addBreak();
				}
				for (int j=size-1;j>=0;j--) {
					XWPFRun run = paras.get(0).insertNewRun(0); 
					run.setText(list.get(j));  
					run.addBreak();
				}
			}
		}
		ss.removeRow(0);
	}
	/**
	 * 文件复制
	 * */
	 public static boolean copyFile(String fileFrom, String fileTo) {  
		 FileInputStream in =null;
		 FileOutputStream out =null;
		 	try {  
	            in = new java.io.FileInputStream(fileFrom);  
	            out = new FileOutputStream(fileTo);  
	            byte[] bt = new byte[1024];  
	            int count;  
	            while ((count = in.read(bt)) > 0) {  
	                out.write(bt, 0, count);  
	            }  
	            return true;  
	        } catch (IOException ex) {  
	            return false;  
	        }finally{
	        	if(in!=null){
	        		try {
						in.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						log.error("失败!", e);
					}  
	        	}
	        	if(out!=null){
	        		try {
						out.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						log.error("失败!", e);
					} 
	        	}
	        }  
	    }  
	 
	 public static void addParagraphOfTable(XWPFDocument document,Integer tableIndex,
				Integer rowIndex,Integer cellIndex,List<FontStyle> list,Boolean centerTag){
		 if(centerTag==null){
			 centerTag=false;
		 }
		if(tableIndex==null){
			tableIndex=document.getTables().size()-1;
		}
		if(rowIndex==null){
			rowIndex=0;
		}
		if(cellIndex==null){
			cellIndex=0;
		}
		XWPFTable table=document.getTables().get(tableIndex);
		XWPFTableRow row=table.getRow(rowIndex);
		XWPFTableCell cell=row.getCell(cellIndex);
		addParagraphOfCell(cell, list,centerTag);
	} 
	
	public static void addParagraphOfCell(XWPFTableCell cell,List<FontStyle> list,Boolean centerTag){
		XWPFParagraph xwpf=null;
		if(list!=null&&list.size()>0){
			for (FontStyle font : list) {
				xwpf=cell.addParagraph();
				if(centerTag){
					xwpf.setAlignment(ParagraphAlignment.CENTER);
				}
				XWPFRun run=xwpf.createRun();
				run.setFontFamily(font.getFontFamily());
				run.setFontSize(font.getFontSize());
				run.setBold(font.getBold());
				run.setText(font.getText());
			}
		}
	}
	/**
	 * 表格插入图片
	 * @param document
	 * @param map
	 * @param doc
	 * @param index
	 */
	public static void replaceImgager( XWPFParagraph paragraph,Map<String, Object> map,ImagerXWPFDocument doc){
		try {
	        int width = Integer.parseInt(map.get("width").toString()); 
	        int height = Integer.parseInt(map.get("height").toString()); 
	        int picType = getPictureType(map.get("type").toString()); 
	        byte[] byteArray = (byte[]) map.get("content"); 
	        ByteArrayInputStream byteInputStream = new ByteArrayInputStream(byteArray);
	        String blipId = doc.addPictureData(byteInputStream,picType);
	        int ind =doc.getNextPicNameNumber(getPictureType(map.get("type").toString()));
	        doc.createPicture(blipId,ind, width , height,paragraph);
		} catch (Exception e) {
			log.error("失败!", e);
		}
	}
	public static void addImagerRow(XWPFTable table,int rowIndex,int getRowIndex){
	    XWPFTableRow rw=null;
		XWPFTableRow rws=table.getRow(getRowIndex);
		rw=table.insertNewTableRow(rowIndex);
		List<XWPFTableCell> rss=rws.getTableCells();
		XWPFTableCell rs=null;
		BigInteger width=BigInteger.valueOf(20);
		for (int j = 0; j < rss.size(); j++) {
			width=rss.get(j).getCTTc().getTcPr().getTcW().getW();
			rs=rw.addNewTableCell();
			CTTcPr cellPr = rs.getCTTc().addNewTcPr();  
			cellPr.addNewVAlign().setVal(STVerticalJc.CENTER);  
			//设置宽度  
			cellPr.addNewTcW().setW(width); 
			XWPFParagraph p=null;
			if(rs.getParagraphs().size()==0){
				p=rs.addParagraph();
			}else{
				p=rs.getParagraphs().get(0);
			}
			p.setAlignment(ParagraphAlignment.CENTER);
		}
	}
	   /**
  * 根据图片类型,取得对应的图片类型代码 
  * @param picType 
  * @return int 
  */ 
 public static int getPictureType(String picType){  
     int res = ImagerXWPFDocument.PICTURE_TYPE_PICT;  
     if(picType != null){ 
         if(picType.equalsIgnoreCase("png")){ 
             res = ImagerXWPFDocument.PICTURE_TYPE_PNG;  
         }else if(picType.equalsIgnoreCase("dib")){ 
             res = ImagerXWPFDocument.PICTURE_TYPE_DIB;  
         }else if(picType.equalsIgnoreCase("emf")){ 
             res = ImagerXWPFDocument.PICTURE_TYPE_EMF;  
         }else if(picType.equalsIgnoreCase("jpg") || picType.equalsIgnoreCase("jpeg")){ 
             res = ImagerXWPFDocument.PICTURE_TYPE_JPEG;  
         }else if(picType.equalsIgnoreCase("wmf")){ 
             res = ImagerXWPFDocument.PICTURE_TYPE_WMF;  
         } 
     } 
     return res;  
 } 
 /**
  * 将输入流中的数据写入字节数组 
  * @param in 
  * @return 
  */ 
 public static byte[] inputStream2ByteArray(InputStream in,boolean isClose){  
     byte[] byteArray = null; 
     try{  
         int total = in.available();  
         byteArray = new byte[total]; 
         in.read(byteArray); 
     }catch(IOException e) {  
         log.error("失败!", e); 
     }finally{ 
         if(isClose){ 
             try{  
                 in.close(); 
             }catch(Exception e2) { 
             	e2.printStackTrace();
             } 
         } 
     } 
     return byteArray;  
 }
}

注意:如果无法正确替换变量,则需要把变量剪切后重新“无格式粘贴”(鼠标右键菜单)

并且关闭word中的检查单词拼写功能