POI替换表格

1 篇文章 0 订阅
/**
 * 生成文档模板(用于文档生成定位书签)
 *
 *<hr>
 * @date 2021年7月27日 上午11:11:46
 * @since 0.0.1
 */
public class GeneralTemplateTool {
	/**
	 * 用一个docx文档作为模板,程序替换其中的内容,再写入目标文档中。
	 * @param filePath
	 * @param outFile
	 * @param params
	 * @throws Exception
	 */
	public void templateWrite(String filePath, String outFile,
	        Map<String, Object> params) throws Exception {
	    InputStream is = new FileInputStream(filePath);
	    //System.out.println(filePath);
	    XWPFDocument doc = new XWPFDocument(is); 
	    // 替换段落里面的变量
	    //this.replaceInPara(doc, params);
	    // 替换多个表格里面的变量并插入数据  
	    this.insertValueToTables(doc, params);
	    OutputStream os = new FileOutputStream(outFile);
	    doc.write(os);
	    this.close(os);
	    this.close(is);
	}

	public static boolean validateTemplateValue(String filePath) {
		InputStream is = null;
		try {
			is = new FileInputStream(filePath);
			//System.out.println(filePath);
			XWPFDocument doc = new XWPFDocument(is);
			List<String> validateWordName = validateWordName(doc);
//			this.close(is);
			String itemTempBooks = "ITEM_ID,ITEM_TEXT";
			String[] split = itemTempBooks.split(",");
			if(validateWordName == null ){
				return false;
			}
			if(validateWordName.size() != split.length){
				return false;
			}
			for (String itemTempBook : split) {
				  if(!validateWordName.contains(itemTempBook)){
					  return false;
			    }
			}
		} catch (Exception e) {
			 return false;
		}finally {
			if(is != null){
//				this.close(is);
			}
		}
		return true; 
	}
	public static void main(String[] args) throws Exception {
		InputStream is = new FileInputStream("D:\\testMerge\\rrr.docx");
		XWPFDocument doc = new XWPFDocument(is);
		insertBookMarkToTables(doc);
	    OutputStream os = new FileOutputStream("D:\\testMerge\\0730.docx");
	    doc.write(os);
		  
//		System.out.println(validateTemplateValue("D:\\testMerge\\新增文档2.docx"));
	}
	/**
	 * 按模版行样式填充数据,暂未实现特殊样式填充(如列合并),只能用于普通样式(如段落间距 缩进 字体 对齐)
	 * @param doc
	 *            要替换的文档
	 * @param params
	 *            参数
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	private void insertValueToTables(XWPFDocument doc, Map<String, Object> params)
	        throws Exception {
	    Iterator<XWPFTable> iterator = doc.getTablesIterator();
	    XWPFTable table = null;
	    int z =1;
	    while (iterator.hasNext()) {
	        //行
	        List<XWPFTableRow> rows = null;
	        //列
	        List<XWPFTableCell> cells = null;
	        List<XWPFParagraph> paras;
	        table = iterator.next();
	        System.out.println("-------解析出第 "+z+" 个表------开始处理");
	        //获取表格行数据list
	        rows = table.getRows();
	        XWPFTableRow tmpRow = null;
	        //第二行为模板行 
	        tmpRow = rows.get(0);
	        //模版列
	        List<XWPFTableCell> tmpCells = null;
	        XWPFTableCell tmpCell = null;
	        tmpCells = tmpRow.getTableCells();    
	        List<Map<String,String>> tablist = (List<Map<String,String>>) params.get("tab1");
	        List<String> listkey = new ArrayList<String>();
	        for (int i = 1; i <= rows.size(); i++) {
	            cells = rows.get(i - 1).getTableCells();
	            if(i==1){
	                //第二行替代值并创建list key用
	                int intcell = 1;
	                for (XWPFTableCell cell : cells) {
	                    System.out.println("第"+intcell + "列:" + cell.getText());
                        //Map mapth = tablist.get(0);
                        paras = cell.getParagraphs();
                        for (XWPFParagraph para : paras) {
                            //读取的值去掉${}
                            String keystr = para.getParagraphText();
                            if(keystr.indexOf("${") != -1){
                            	keystr = keystr.substring(keystr.indexOf("{")+1, keystr.lastIndexOf("}"));
                            	listkey.add(keystr); 
	                            if(tablist.get(0).containsKey(keystr)){
	                            	if(!listkey.contains(keystr)){
	                            		listkey.add(keystr);
	                            	}
		                            List<XWPFRun> runs;
		                            runs = para.getRuns();
		                            int n = runs.size();
		                            for (int m = 0; m < n; m++) {
		                            	para.removeRun(0);
		                            }
		                            CTBookmark ctBookmark = para.getCTP().addNewBookmarkStart();
		                            ctBookmark.setName(tablist.get(0).get(keystr).toString());
		                            int num = (int) System.currentTimeMillis();
		                            ctBookmark.setId(BigInteger.valueOf(num));
		                            XWPFRun newRun = para.createRun();
		                            para.getCTP().addNewBookmarkEnd().setId(BigInteger.valueOf(num));
	                            }
                            }
                        }
                        intcell++;
                    }
	            }
	        }
	        for (int i = 1; i < tablist.size(); i++) {
	        	System.out.println("开始复制第" + i + "行"); 
	        	XWPFTableRow row = table.createRow(); 
	        	row.setHeight(tmpRow.getHeight()); 
	        	Map<String,String> tempmap = tablist.get(i); 
	        	cells = row.getTableCells(); 
	        	// 插入的行会填充与表格第一行相同的列数 
	        	for (int k = 0 ; k < cells.size(); k++) { 
	        		tmpCell = tmpCells.get(k); 
	        		XWPFTableCell cell = cells.get(k); 
	        		paras = cell.getParagraphs();
                    for (XWPFParagraph para : paras) {
                    	CTBookmark ctBookmark = para.getCTP().addNewBookmarkStart();
                        ctBookmark.setName(tablist.get(i).get(listkey.get(k)).toString());
                        int num = (int) System.currentTimeMillis();
                        ctBookmark.setId(BigInteger.valueOf(num));
                        XWPFRun newRun = para.createRun();
                        para.getCTP().addNewBookmarkEnd().setId(BigInteger.valueOf(num));
                    }
	        		//setCellText(tmpCell, cell, tablist.get(i).get(listkey.get(k)).toString()); 
	        		System.out.println("第"+(k+1)+"列:" +tablist.get(i).get(listkey.get(k)).toString()); 
	        	}
        	}
	        // 删除表标识行
	        //table.removeRow(1);
	        //System.out.println("-------解析出第 "+z+" 个表------结束处理");
	        z++;
	    }
	}

	/**
	 * 关闭输入流
	 * 
	 * @param is
	 */
	private void close(InputStream is) {
	    if (is != null) {
	        try {
	            is.close();
	        } catch (IOException e) {
	            e.printStackTrace();
	        }
	    }
	}

	/**
	* 关闭输出流
	* 
	* @param os
	*/
	private void close(OutputStream os) {
	     if (os != null) {
	        try {
	               os.close();
	            } catch (IOException e) {
	                e.printStackTrace();
	            }
	        }
	    }
	@SuppressWarnings("unchecked")
	private static List<String> validateWordName(XWPFDocument doc)
	        throws Exception {
	    Iterator<XWPFTable> iterator = doc.getTablesIterator();
	    XWPFTable table = null;
	    int z =1;
	    while (iterator.hasNext()) {
	        //行
	        List<XWPFTableRow> rows = null;
	        //列
	        List<XWPFTableCell> cells = null;
	        List<XWPFParagraph> paras;
	        table = iterator.next();
	        System.out.println("-------解析出第 "+z+" 个表------开始处理");
	        //获取表格行数据list
	        rows = table.getRows();
	        XWPFTableRow tmpRow = null;
	        //第二行为模板行 
	        tmpRow = rows.get(0);
	        //模版列
	        List<XWPFTableCell> tmpCells = null;
	        XWPFTableCell tmpCell = null;
	        tmpCells = tmpRow.getTableCells();    
	        List<String> listkey = new ArrayList<String>();
	        for (int i = 1; i <= rows.size(); i++) {
	            cells = rows.get(i - 1).getTableCells();
	            if(i==1){
	                //第二行替代值并创建list key用
	                int intcell = 1;
	                for (XWPFTableCell cell : cells) {
	                    System.out.println("第"+intcell + "列:" + cell.getText());
                        //Map mapth = tablist.get(0);
                        paras = cell.getParagraphs();
                        for (XWPFParagraph para : paras) {
                            //读取的值去掉${}
                            String keystr = para.getParagraphText();
                            if(keystr.indexOf("${") != -1){
                            	keystr = keystr.substring(keystr.indexOf("{")+1, keystr.lastIndexOf("}"));
                            	listkey.add(keystr); 
                            }
                        }
                        intcell++;
                    }
	            }
	        }
	       return listkey;
	    }
		return null;
	}
	/**
	 * 根据表格插入书签
	 *
	 *<hr>
	 * @author Hanjidong
	 * @date 2021年7月30日 下午4:51:34
	 * @since 0.0.1
	 * @param doc
	 * @param params
	 * @throws Exception
	 * void
	 */
	@SuppressWarnings("unchecked")
	public static void insertBookMarkToTables(XWPFDocument doc)
	        throws Exception {
	    Iterator<XWPFTable> iterator = doc.getTablesIterator();
	    XWPFTable table = null;
	    int z =1;
	    while (iterator.hasNext()) {
	        //行
	        List<XWPFTableRow> rows = null;
	        //列
	        List<XWPFTableCell> cells = null;
	        List<XWPFParagraph> paras;
	        table = iterator.next();
	        System.out.println("-------解析出第 "+z+" 个表------开始处理");
	        //获取表格行数据list
	        rows = table.getRows();
	        String styleValue = getStyleValue(doc, "表");
	        table.setStyleID(styleValue);
	        //模版列
	          
	        for (int i = 1; i <= rows.size(); i++) {
	            cells = rows.get(i - 1).getTableCells();
	            if(i==1){
	                //第二行替代值并创建list key用
	                int intcell = 1;
	                for (XWPFTableCell cell : cells) {
	                    System.out.println("第"+intcell + "列:" + cell.getText());
                        //Map mapth = tablist.get(0);
                        paras = cell.getParagraphs();
                        for (XWPFParagraph para : paras) {
                        	CTBookmark ctBookmark = para.getCTP().addNewBookmarkStart();
                            ctBookmark.setName("第"+intcell + "列:" + cell.getText());
                            int num = (int) System.currentTimeMillis();
                            ctBookmark.setId(BigInteger.valueOf(num));
                            XWPFRun newRun = para.createRun();
                            para.getCTP().addNewBookmarkEnd().setId(BigInteger.valueOf(num));
                        }
                        intcell++;
                    }
	            }
	        }
	       
	        z++;
	    }
	}
	 /**
     * 查找文档样式值
     * @param document 文档类
     * @param styleName 样式名称
     * @return 样式值
     * @throws IOException
     * @throws XmlException
     */
    public static String getStyleValue(XWPFDocument document, String styleName) throws IOException, XmlException {
    	
        if (styleName == null || styleName.length() == 0) {
            return null;
        }
        CTStyles styles = document.getStyle();
        CTStyle[] styleArray = styles.getStyleArray();
        for (CTStyle style : styleArray) {
            if (style.getName().getVal().equals(styleName)) {
                return style.getStyleId();
            }
        }
        return null;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值