EasyPOI word模板导出 隐藏单元格边框、隐藏表格某一行边框

问题

最近在用EasyPOI的word模板导出功能,遇到了这样的一个需求:在用指令fe:List遍历输出List时,要在中间进行表格的分隔。如果直接把一个表格分成2个,一是可能会影响后面的输出,二是这个表格的表头就不能出现在每一页了(你没听错,我们的甲方就是这么多事情)。
所以我就想到了隐藏左右下边框的办法。
实现效果如图:
EasyPOI word模板导出 隐藏单元格边框、隐藏表格某一行边框_第1张图片
也可以把“本部门结束”换成你想要的,但要修改代码中这个地方的判定条件

解决方法

我是直接修改了EasyPOI的源代码,因为它不支持在原有的类上直接修改,
我就将它的代码复制到我的类中,然后进行修改,但这就导致了虽然我只增加了核心代码,但是我要复制它的2~3个类,虽然我把它写了出来,但是还是建议直接下载然后调用
这3个类的下载地址:建议直接下载调用即可
https://download.csdn.net/download/qijingpei/10408691

核心代码

将ExcelMapParse类复制到我新建的ExcelMapParseTest类,
在parseNextRowAndAddRow()方法中的第一个for循环的最后加入这段代码

if(currentRow.getCell(0).getText().equals("本检测室结束")) {
   CTTcBorders tblBorders = currentRow.getCell(0).getCTTc().getTcPr().addNewTcBorders();
   tblBorders.addNewLeft().setVal(STBorder.NIL);
   tblBorders.addNewRight().setVal(STBorder.NIL);
   tblBorders.addNewBottom().setVal(STBorder.NIL);
   //隐藏这一行所有单元格的边框
   for(int i=0; i
     currentRow.getCell(i).getCTTc().getTcPr().setTcBorders(tblBorders);
   }
}

全部代码(建议直接下载上面的类包)

  1. 调用EasyPOI改为调用咱们自己的类
//XWPFDocument doc = WordExportUtil.exportWord07(baseDir + template.getPath(), map);
//改成下面这些:
XWPFDocument doc = new ParseWord07Test().parseWord(baseDir + template.getPath(), map);
  1. ParseWord07Test()类的代码

import static cn.afterturn.easypoi.util.PoiElUtil.EMPTY;
import static cn.afterturn.easypoi.util.PoiElUtil.END_STR;
import static cn.afterturn.easypoi.util.PoiElUtil.FOREACH;
import static cn.afterturn.easypoi.util.PoiElUtil.FOREACH_AND_SHIFT;
import static cn.afterturn.easypoi.util.PoiElUtil.FOREACH_NOT_CREATE;
import static cn.afterturn.easypoi.util.PoiElUtil.START_STR;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFFooter;
import org.apache.poi.xwpf.usermodel.XWPFHeader;
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.CTTcBorders;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STBorder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.afterturn.easypoi.cache.WordCache;
import cn.afterturn.easypoi.entity.ImageEntity;
import cn.afterturn.easypoi.util.PoiPublicUtil;
import cn.afterturn.easypoi.word.entity.MyXWPFDocument;
import cn.afterturn.easypoi.word.entity.params.ExcelListEntity;
import cn.afterturn.easypoi.word.parse.excel.ExcelEntityParse;

/**
* 解析07版的Word,替换文字,生成表格,生成图片
* 
* @author JueYue
*  2013-11-16
* @version 1.0
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public class ParseWord07Test {

   private static final Logger LOGGER = LoggerFactory.getLogger(ParseWord07Test.class);

   /**
    * 添加图片
    * 
    * @author JueYue
    *  2013-11-20
    * @param obj
    * @param currentRun
    * @throws Exception
    */
   private void addAnImage(ImageEntity obj, XWPFRun currentRun) throws Exception {
       Object[] isAndType = PoiPublicUtil.getIsAndType(obj);
       String picId;
       try {
           picId = currentRun.getDocument().addPictureData((byte[]) isAndType[0],
               (Integer) isAndType[1]);
           ((MyXWPFDocument) currentRun.getDocument()).createPicture(currentRun,
               picId, currentRun.getDocument()
                   .getNextPicNameNumber((Integer) isAndType[1]),
               obj.getWidth(), obj.getHeight());

       } catch (Exception e) {
           LOGGER.error(e.getMessage(), e);
       }

   }

   /**
    * 根据条件改变值
    * 
    * @param map
    * @author JueYue
    *  2013-11-16
    */
   private void changeValues(XWPFParagraph paragraph, XWPFRun currentRun, String currentText,
                             List<Integer> runIndex, Map<String, Object> map) throws Exception {
       Object obj = PoiPublicUtil.getRealValue(currentText, map);
       if (obj instanceof ImageEntity) {// 如果是图片就设置为图片
           currentRun.setText("", 0);
           addAnImage((ImageEntity) obj, currentRun);
       } else {
           //功能:隐藏某一行(非fe:list循环遍历出来的行)的左边框和右边框
//         if(obj.toString().equals("本检测室结束")) {//移除左右边框,这样看起来像是分割了一个表格
//             CTTcBorders tblBorders = cell.getCTTc().getTcPr().addNewTcBorders();
//               tblBorders.addNewLeft().setVal(STBorder.NIL);
//               tblBorders.addNewRight().setVal(STBorder.NIL);
//               XWPFTableRow currentRow = cell.getTableRow();
//               currentRow.getCell(0).getCTTc().getTcPr().setTcBorders(tblBorders);
//               for(int i=currentRow.getTableCells().size() -1; i >= 1; i--) {//移除后面的单元格
//                 currentRow.removeCell(i);
//               }
//               System.out.println("cell.getCTTc().getTcPr().isSetTcBorders():" + cell.getCTTc().getTcPr().isSetTcBorders());;
//         }
           currentText = obj.toString();
           PoiPublicUtil.setWordText(currentRun, currentText);
       }
       for (int k = 0; k < runIndex.size(); k++) {
           paragraph.getRuns().get(runIndex.get(k)).setText("", 0);
       }
       runIndex.clear();
   }

   /**
    * 判断是不是迭代输出
    * 
    * @author JueYue
    *  2013-11-18
    * @return
    * @throws Exception
    */
   private Object checkThisTableIsNeedIterator(XWPFTableCell cell,
                                               Map<String, Object> map) throws Exception {
       String text = cell.getText().trim();
       // 判断是不是迭代输出
       if (text != null && text.contains(FOREACH) && text.startsWith(START_STR)) {
           text = text.replace(FOREACH_NOT_CREATE, EMPTY).replace(FOREACH_AND_SHIFT, EMPTY)
               .replace(FOREACH, EMPTY).replace(START_STR, EMPTY);
           String[] keys = text.replaceAll("\\s{1,}", " ").trim().split(" ");
           return PoiPublicUtil.getParamsValue(keys[0], map);
       }
       return null;
   }

   /**
    * 解析所有的文本
    * 
    * @author JueYue
    *  2013-11-17
    * @param paragraphs
    * @param map
    */
   private void parseAllParagraphic(List<XWPFParagraph> paragraphs,
                                    Map<String, Object> map) throws Exception {
       XWPFParagraph paragraph;
       for (int i = 0; i < paragraphs.size(); i++) {
           paragraph = paragraphs.get(i);
           if (paragraph.getText().indexOf(START_STR) != -1) {
               parseThisParagraph(paragraph, map);
//             parseThisParagraph(paragraph, map, cell);
           }

       }

   }

   /**
    * 解析这个段落
    * 
    * @author JueYue
    *  2013-11-16
    * @param paragraph
    * @param map
    */
   private void parseThisParagraph(XWPFParagraph paragraph,
                                   Map<String, Object> map) throws Exception {
       XWPFRun run;
       XWPFRun currentRun = null;// 拿到的第一个run,用来set值,可以保存格式
       String currentText = "";// 存放当前的text
       String text;
       Boolean isfinde = false;// 判断是不是已经遇到{{
       List<Integer> runIndex = new ArrayList<Integer>();// 存储遇到的run,把他们置空
       for (int i = 0; i < paragraph.getRuns().size(); i++) {
           run = paragraph.getRuns().get(i);
           text = run.getText(0);
           if (StringUtils.isEmpty(text)) {
               continue;
           } // 如果为空或者""这种这继续循环跳过
           if (isfinde) {
               currentText += text;
               if (currentText.indexOf(START_STR) == -1) {
                   isfinde = false;
                   runIndex.clear();
               } else {
                   runIndex.add(i);
               }
               if (currentText.indexOf(END_STR) != -1) {
                   changeValues(paragraph, currentRun, currentText, runIndex, map);
//                 changeValues(paragraph, currentRun, currentText, runIndex, map, cell);
                   currentText = "";
                   isfinde = false;
               }
           } else if (text.indexOf(START_STR) >= 0) {// 判断是不是开始
               currentText = text;
               isfinde = true;
               currentRun = run;
           } else {
               currentText = "";
           }
           if (currentText.indexOf(END_STR) != -1) {
               changeValues(paragraph, currentRun, currentText, runIndex, map);
//               changeValues(paragraph, currentRun, currentText, runIndex, map, cell);
               isfinde = false;
           }
       }

   }

   private void parseThisRow(List<XWPFTableCell> cells, Map<String, Object> map) throws Exception {
       for (XWPFTableCell cell : cells) {
           parseAllParagraphic(cell.getParagraphs(), map);
       }
   }

   /**
    * 解析这个表格
    * 
    * @author JueYue
    *  2013-11-17
    * @param table
    * @param map
    */
   private void parseThisTable(XWPFTable table, Map<String, Object> map) throws Exception {
       XWPFTableRow row;
       List<XWPFTableCell> cells;
       Object listobj;
       for (int i = 0; i < table.getNumberOfRows(); i++) {
           row = table.getRow(i);
           cells = row.getTableCells();
           listobj = checkThisTableIsNeedIterator(cells.get(0), map);
           if (listobj == null) {
               parseThisRow(cells, map);
           } else if (listobj instanceof ExcelListEntity) {
               new ExcelEntityParse().parseNextRowAndAddRow(table, i, (ExcelListEntity) listobj);
               i = i + ((ExcelListEntity) listobj).getList().size() - 1;//删除之后要往上挪一行,然后加上跳过新建的行数
           } else {
               ExcelMapParseTest.parseNextRowAndAddRow(table, i, (List) listobj);
               i = i + ((List) listobj).size() - 1;//删除之后要往上挪一行,然后加上跳过新建的行数
           }
       }
   }

   /**
    * 解析07版的Word并且进行赋值
    * 
    * @author JueYue
    *  2013-11-16
    * @return
    * @throws Exception
    */
   public XWPFDocument parseWord(String url, Map<String, Object> map) throws Exception {
       MyXWPFDocument doc = WordCache.getXWPFDocumen(url);
       parseWordSetValue(doc, map);
       return doc;
   }

   /**
    * 解析07版的Word并且进行赋值
    * @throws Exception
    */
   public void parseWord(XWPFDocument document, Map<String, Object> map) throws Exception {
       parseWordSetValue((MyXWPFDocument) document, map);
   }

   private void parseWordSetValue(MyXWPFDocument doc, Map<String, Object> map) throws Exception {
       // 第一步解析文档
       parseAllParagraphic(doc.getParagraphs(), map);
       // 第二步解析页眉,页脚
       parseHeaderAndFoot(doc, map);
       // 第三步解析所有表格
       XWPFTable table;
       Iterator<XWPFTable> itTable = doc.getTablesIterator();
       while (itTable.hasNext()) {
           table = itTable.next();
           if (table.getText().indexOf(START_STR) != -1) {
               parseThisTable(table, map);
           }
       }

   }

   /**
    * 解析页眉和页脚
    * @param doc
    * @param map
    * @throws Exception
    */
   private void parseHeaderAndFoot(MyXWPFDocument doc, Map<String, Object> map) throws Exception {
       List<XWPFHeader> headerList = doc.getHeaderList();
       for (XWPFHeader xwpfHeader : headerList) {
           for (int i = 0; i < xwpfHeader.getListParagraph().size(); i++) {
//               parseThisParagraph(xwpfHeader.getListParagraph().get(i), map);
           }
       }
       List<XWPFFooter> footerList = doc.getFooterList();
       for (XWPFFooter xwpfFooter : footerList) {
           for (int i = 0; i < xwpfFooter.getListParagraph().size(); i++) {
//               parseThisParagraph(xwpfFooter.getListParagraph().get(i), map);
           }
       }

   }
}

  1. 上面类中用到的ExcelMapParseTest 类也需要我们修改

import com.google.common.collect.Maps;

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.CTTcBorders;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STBorder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import cn.afterturn.easypoi.entity.ImageEntity;
import cn.afterturn.easypoi.util.PoiWordStyleUtil;

import static cn.afterturn.easypoi.util.PoiElUtil.EMPTY;
import static cn.afterturn.easypoi.util.PoiElUtil.END_STR;
import static cn.afterturn.easypoi.util.PoiElUtil.FOREACH;
import static cn.afterturn.easypoi.util.PoiElUtil.FOREACH_AND_SHIFT;
import static cn.afterturn.easypoi.util.PoiElUtil.FOREACH_NOT_CREATE;
import static cn.afterturn.easypoi.util.PoiElUtil.START_STR;
import static cn.afterturn.easypoi.util.PoiElUtil.eval;

/**
* 处理和生成Map 类型的数据变成表格
* @author JueYue
*  2014年8月9日 下午10:28:46
*/
public final class ExcelMapParseTest {

   private static final Logger LOGGER = LoggerFactory.getLogger(ExcelMapParseTest.class);

   /**
    * 解析参数行,获取参数列表
    *
    * @author JueYue
    *  2013-11-18
    * @param currentRow
    * @return
    */
   private static String[] parseCurrentRowGetParams(XWPFTableRow currentRow) {
       List cells = currentRow.getTableCells();
       String[] params = new String[cells.size()];
       String text;
       for (int i = 0; i < cells.size(); i++) {
           text = cells.get(i).getText();
           params[i] = text == null ? ""
                   : text.trim().replace(START_STR, EMPTY).replace(END_STR, EMPTY);
       }
       return params;
   }

   /**
    * 解析下一行,并且生成更多的行
    * @param table
    * @param index
    * @param list
    */
   public static void parseNextRowAndAddRow(XWPFTable table, int index,
                                            List list) throws Exception {
       XWPFTableRow currentRow = table.getRow(index);
       String[] params = parseCurrentRowGetParams(currentRow);
       String listname = params[0];
       boolean isCreate = !listname.contains(FOREACH_NOT_CREATE);//!fe下isCreate是false
       listname = listname.replace(FOREACH_NOT_CREATE, EMPTY).replace(FOREACH_AND_SHIFT, EMPTY)
               .replace(FOREACH, EMPTY).replace(START_STR, EMPTY);
       String[] keys = listname.replaceAll("\\s{1,}", " ").trim().split(" ");
       params[0] = keys[1];
       //保存这一行的样式是-后面好统一设置
       List tempCellList = new ArrayList();
       tempCellList.addAll(table.getRow(index).getTableCells());
       int templateInde = index;
       int cellIndex = 0;// 创建完成对象一行好像多了一个cell
       Map tempMap = Maps.newHashMap();
       LOGGER.debug("start for each data list :{}", list.size());

       for (Object obj : list) {
//         currentRow = isCreate ? table.insertNewTableRow(index++) : table.getRow(index++);
            //上面我改为了下面,是为了适应!fe的情况:
           currentRow = isCreate ? table.insertNewTableRow(index++) : table.getRow(index++ + 1);
           tempMap.put("t", obj);
           //尝试用这个来进行合并单元格 
           //currentRow.removeCell(1);
//           System.out.println("currentRow.getTableCells().size():" + currentRow.getTableCells().size());
           //加了 
           if(currentRow == null) {
               continue;
           }
           //加了: currentRow!=null可以用来预防行数不够 
           for (cellIndex = 0; currentRow!=null && cellIndex < currentRow.getTableCells().size(); cellIndex++) {
               String val = eval(params[cellIndex], tempMap).toString();
               currentRow.getTableCells().get(cellIndex).setText("");
               PoiWordStyleUtil.copyCellAndSetValue(tempCellList.get(cellIndex),
                       currentRow.getTableCells().get(cellIndex), val);
           }

           for (; cellIndex < params.length; cellIndex++) {
               if (eval(params[cellIndex], tempMap) instanceof ImageEntity) {
                   PoiWordStyleUtilTest.copyCellAndSetValue(tempCellList.get(cellIndex),currentRow.createCell(), 
                           eval(params[cellIndex], tempMap));
               } else {
                   String val = eval(params[cellIndex], tempMap).toString();
                   PoiWordStyleUtilTest.copyCellAndSetValue(tempCellList.get(cellIndex),
                           currentRow.createCell(), val);
               }
           }
           if(currentRow.getCell(0).getText().equals("本检测室结束")) {//隐藏这一行的左边框、右边框和下边框
               CTTcBorders tblBorders = currentRow.getCell(0).getCTTc().getTcPr().addNewTcBorders();
               tblBorders.addNewLeft().setVal(STBorder.NIL);
               tblBorders.addNewRight().setVal(STBorder.NIL);
               tblBorders.addNewBottom().setVal(STBorder.NIL);
               for(int i=0; i
                   currentRow.getCell(i).getCTTc().getTcPr().setTcBorders(tblBorders);
               }
           }
       }
//       table.removeRow(index);// 移除这一行
       //我自己改写的:本来是:table.removeRow(index);// 移除这一行
       if(!isCreate) {//如果是!fe,即没有创建新的行
           table.removeRow(templateInde);// 移除模板指令这一行 
       } else {
           table.removeRow(index);// 移除这一行
       }

   }

}

  1. PoiWordStyleUtilTest 类(虽然这个类不是必须的,但这个修改过的类能让word遍历List能导出图片。如果不需要这个功能的话,可以把上各类中调用此PoiWordStyleUtilTest 类的地方,还是直接调用原来的EasyPOI的类)

import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFonts;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTInd;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPPr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRPr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSpacing;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTc;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTcPr;

import cn.afterturn.easypoi.entity.ImageEntity;
import cn.afterturn.easypoi.util.PoiPublicUtil;
import cn.afterturn.easypoi.word.entity.MyXWPFDocument;

/**
 * Word 样式copy Created by JueYue on 2017/9/19.
 */
public class PoiWordStyleUtilTest {


    public static void copyCellAndSetValue(XWPFTableCell tmpCell, XWPFTableCell cell, String text) throws Exception {
        CTTc cttc2 = tmpCell.getCTTc();
        CTTcPr ctPr2 = cttc2.getTcPr();

        CTTc cttc = cell.getCTTc();
        CTTcPr ctPr = cttc.addNewTcPr();
        if (tmpCell.getColor() != null) {
            cell.setColor(tmpCell.getColor());
        }
        if (tmpCell.getVerticalAlignment() != null) {
            cell.setVerticalAlignment(tmpCell.getVerticalAlignment());
        }
        if (ctPr2.getTcW() != null) {
            ctPr.addNewTcW().setW(ctPr2.getTcW().getW());
        }
        if (ctPr2.getVAlign() != null) {
            ctPr.addNewVAlign().setVal(ctPr2.getVAlign().getVal());
        }
        if (cttc2.getPList().size() > 0) {
            CTP ctp = cttc2.getPList().get(0);
            if (ctp.getPPr() != null) {
                if (ctp.getPPr().getJc() != null) {
                    cttc.getPList().get(0).addNewPPr().addNewJc().setVal(ctp.getPPr().getJc().getVal());
                }
            }
        }

        if (ctPr2.getTcBorders() != null) {
            ctPr.setTcBorders(ctPr2.getTcBorders());
        }

        XWPFParagraph tmpP = tmpCell.getParagraphs().get(0);
        XWPFParagraph cellP = cell.getParagraphs().get(0);
        XWPFRun tmpR = null;
        if (tmpP.getRuns() != null && tmpP.getRuns().size() > 0) {
            tmpR = tmpP.getRuns().get(0);
        }
        XWPFRun cellR = cellP.createRun();
        cellR.setText(text);
        //复制字体信息
        if (tmpR != null) {
            cellR.setBold(tmpR.isBold());
            cellR.setItalic(tmpR.isItalic());
            cellR.setStrike(tmpR.isStrike());
            cellR.setUnderline(tmpR.getUnderline());
            cellR.setColor(tmpR.getColor());
            cellR.setTextPosition(tmpR.getTextPosition());
            if (tmpR.getFontSize() != -1) {
                cellR.setFontSize(tmpR.getFontSize());
            }
            if (tmpR.getFontFamily() != null) {
                cellR.setFontFamily(tmpR.getFontFamily());
            }
            if (tmpR.getCTR() != null) {
                if (tmpR.getCTR().isSetRPr()) {
                    CTRPr tmpRPr = tmpR.getCTR().getRPr();
                    if (tmpRPr.isSetRFonts()) {
                        CTFonts tmpFonts = tmpRPr.getRFonts();
                        CTRPr cellRPr = cellR.getCTR().isSetRPr() ? cellR.getCTR().getRPr() : cellR.getCTR().addNewRPr();
                        CTFonts cellFonts = cellRPr.isSetRFonts() ? cellRPr.getRFonts() : cellRPr.addNewRFonts();
                        cellFonts.setAscii(tmpFonts.getAscii());
                        cellFonts.setAsciiTheme(tmpFonts.getAsciiTheme());
                        cellFonts.setCs(tmpFonts.getCs());
                        cellFonts.setCstheme(tmpFonts.getCstheme());
                        cellFonts.setEastAsia(tmpFonts.getEastAsia());
                        cellFonts.setEastAsiaTheme(tmpFonts.getEastAsiaTheme());
                        cellFonts.setHAnsi(tmpFonts.getHAnsi());
                        cellFonts.setHAnsiTheme(tmpFonts.getHAnsiTheme());
                    }
                }
            }
        }
        //复制段落信息
        if (tmpP.getAlignment() != null) {
            cellP.setAlignment(tmpP.getAlignment());
        }
        if (tmpP.getVerticalAlignment() != null) {
            cellP.setVerticalAlignment(tmpP.getVerticalAlignment());
        }
        if (tmpP.getBorderBetween() != null) {
            cellP.setBorderBetween(tmpP.getBorderBetween());
        }
        if (tmpP.getBorderBottom() != null){
            cellP.setBorderBottom(tmpP.getBorderBottom());
        }
        if (tmpP.getBorderLeft() != null){
            cellP.setBorderLeft(tmpP.getBorderLeft());
        }
        if (tmpP.getBorderRight() != null){
            cellP.setBorderRight(tmpP.getBorderRight());
        }
        if (tmpP.getBorderTop() != null){
            cellP.setBorderTop(tmpP.getBorderTop());
        }
        cellP.setPageBreak(tmpP.isPageBreak());
        if (tmpP.getCTP() != null) {
            if (tmpP.getCTP().getPPr() != null) {
                CTPPr tmpPPr = tmpP.getCTP().getPPr();
                CTPPr cellPPr = cellP.getCTP().getPPr() != null ? cellP.getCTP().getPPr() : cellP.getCTP().addNewPPr();
                //复制段落间距信息
                CTSpacing tmpSpacing = tmpPPr.getSpacing();
                if (tmpSpacing != null) {
                    CTSpacing cellSpacing = cellPPr.getSpacing() != null ? cellPPr.getSpacing() : cellPPr.addNewSpacing();
                    if (tmpSpacing.getAfter() != null) {
                        cellSpacing.setAfter(tmpSpacing.getAfter());
                    }
                    if (tmpSpacing.getAfterAutospacing() != null) {
                        cellSpacing.setAfterAutospacing(tmpSpacing.getAfterAutospacing());
                    }
                    if (tmpSpacing.getAfterLines() != null) {
                        cellSpacing.setAfterLines(tmpSpacing.getAfterLines());
                    }
                    if (tmpSpacing.getBefore() != null) {
                        cellSpacing.setBefore(tmpSpacing.getBefore());
                    }
                    if (tmpSpacing.getBeforeAutospacing() != null) {
                        cellSpacing.setBeforeAutospacing(tmpSpacing.getBeforeAutospacing());
                    }
                    if (tmpSpacing.getBeforeLines() != null) {
                        cellSpacing.setBeforeLines(tmpSpacing.getBeforeLines());
                    }
                    if (tmpSpacing.getLine() != null) {
                        cellSpacing.setLine(tmpSpacing.getLine());
                    }
                    if (tmpSpacing.getLineRule() != null) {
                        cellSpacing.setLineRule(tmpSpacing.getLineRule());
                    }
                }
                //复制段落缩进信息
                CTInd tmpInd = tmpPPr.getInd();
                if (tmpInd != null) {
                    CTInd cellInd = cellPPr.getInd() != null ? cellPPr.getInd() : cellPPr.addNewInd();
                    if (tmpInd.getFirstLine() != null) {
                        cellInd.setFirstLine(tmpInd.getFirstLine());
                    }
                    if (tmpInd.getFirstLineChars() != null) {
                        cellInd.setFirstLineChars(tmpInd.getFirstLineChars());
                    }
                    if (tmpInd.getHanging() != null) {
                        cellInd.setHanging(tmpInd.getHanging());
                    }
                    if (tmpInd.getHangingChars() != null) {
                        cellInd.setHangingChars(tmpInd.getHangingChars());
                    }
                    if (tmpInd.getLeft() != null) {
                        cellInd.setLeft(tmpInd.getLeft());
                    }
                    if (tmpInd.getLeftChars() != null) {
                        cellInd.setLeftChars(tmpInd.getLeftChars());
                    }
                    if (tmpInd.getRight() != null) {
                        cellInd.setRight(tmpInd.getRight());
                    }
                    if (tmpInd.getRightChars() != null) {
                        cellInd.setRightChars(tmpInd.getRightChars());
                    }
                }
            }
        }
    }

    /**
     * fe支持图片功能
     * @param tmpCell
     * @param createCell
     * @param eval
     */
    public static void copyCellAndSetValue(XWPFTableCell tmpCell, XWPFTableCell cell, Object text) throws Exception {
        CTTc cttc2 = tmpCell.getCTTc();
        CTTcPr ctPr2 = cttc2.getTcPr();

        CTTc cttc = cell.getCTTc();
        CTTcPr ctPr = cttc.addNewTcPr();
        if (tmpCell.getColor() != null) {
            cell.setColor(tmpCell.getColor());
        }
        if (tmpCell.getVerticalAlignment() != null) {
            cell.setVerticalAlignment(tmpCell.getVerticalAlignment());
        }
        if (ctPr2.getTcW() != null) {
            ctPr.addNewTcW().setW(ctPr2.getTcW().getW());
        }
        if (ctPr2.getVAlign() != null) {
            ctPr.addNewVAlign().setVal(ctPr2.getVAlign().getVal());
        }
        if (cttc2.getPList().size() > 0) {
            CTP ctp = cttc2.getPList().get(0);
            if (ctp.getPPr() != null) {
                if (ctp.getPPr().getJc() != null) {
                    cttc.getPList().get(0).addNewPPr().addNewJc().setVal(ctp.getPPr().getJc().getVal());
                }
            }
        }

        if (ctPr2.getTcBorders() != null) {
            ctPr.setTcBorders(ctPr2.getTcBorders());
        }

        XWPFParagraph tmpP = tmpCell.getParagraphs().get(0);
        XWPFParagraph cellP = cell.getParagraphs().get(0);
        XWPFRun tmpR = null;
        if (tmpP.getRuns() != null && tmpP.getRuns().size() > 0) {
            tmpR = tmpP.getRuns().get(0);
        }
        XWPFRun cellR = cellP.createRun();
        addAnImage((ImageEntity) text, cellR);
        //复制字体信息
        if (tmpR != null) {
            cellR.setBold(tmpR.isBold());
            cellR.setItalic(tmpR.isItalic());
            cellR.setStrike(tmpR.isStrike());
            cellR.setUnderline(tmpR.getUnderline());
            cellR.setColor(tmpR.getColor());
            cellR.setTextPosition(tmpR.getTextPosition());
            if (tmpR.getFontSize() != -1) {
                cellR.setFontSize(tmpR.getFontSize());
            }
            if (tmpR.getFontFamily() != null) {
                cellR.setFontFamily(tmpR.getFontFamily());
            }
            if (tmpR.getCTR() != null) {
                if (tmpR.getCTR().isSetRPr()) {
                    CTRPr tmpRPr = tmpR.getCTR().getRPr();
                    if (tmpRPr.isSetRFonts()) {
                        CTFonts tmpFonts = tmpRPr.getRFonts();
                        CTRPr cellRPr = cellR.getCTR().isSetRPr() ? cellR.getCTR().getRPr() : cellR.getCTR().addNewRPr();
                        CTFonts cellFonts = cellRPr.isSetRFonts() ? cellRPr.getRFonts() : cellRPr.addNewRFonts();
                        cellFonts.setAscii(tmpFonts.getAscii());
                        cellFonts.setAsciiTheme(tmpFonts.getAsciiTheme());
                        cellFonts.setCs(tmpFonts.getCs());
                        cellFonts.setCstheme(tmpFonts.getCstheme());
                        cellFonts.setEastAsia(tmpFonts.getEastAsia());
                        cellFonts.setEastAsiaTheme(tmpFonts.getEastAsiaTheme());
                        cellFonts.setHAnsi(tmpFonts.getHAnsi());
                        cellFonts.setHAnsiTheme(tmpFonts.getHAnsiTheme());
                    }
                }
            }
        }
        //复制段落信息
        if (tmpP.getAlignment() != null) {
            cellP.setAlignment(tmpP.getAlignment());
        }
        if (tmpP.getVerticalAlignment() != null) {
            cellP.setVerticalAlignment(tmpP.getVerticalAlignment());
        }
        if (tmpP.getBorderBetween() != null) {
            cellP.setBorderBetween(tmpP.getBorderBetween());
        }
        if (tmpP.getBorderBottom() != null){
            cellP.setBorderBottom(tmpP.getBorderBottom());
        }
        if (tmpP.getBorderLeft() != null){
            cellP.setBorderLeft(tmpP.getBorderLeft());
        }
        if (tmpP.getBorderRight() != null){
            cellP.setBorderRight(tmpP.getBorderRight());
        }
        if (tmpP.getBorderTop() != null){
            cellP.setBorderTop(tmpP.getBorderTop());
        }
        cellP.setPageBreak(tmpP.isPageBreak());
        if (tmpP.getCTP() != null) {
            if (tmpP.getCTP().getPPr() != null) {
                CTPPr tmpPPr = tmpP.getCTP().getPPr();
                CTPPr cellPPr = cellP.getCTP().getPPr() != null ? cellP.getCTP().getPPr() : cellP.getCTP().addNewPPr();
                //复制段落间距信息
                CTSpacing tmpSpacing = tmpPPr.getSpacing();
                if (tmpSpacing != null) {
                    CTSpacing cellSpacing = cellPPr.getSpacing() != null ? cellPPr.getSpacing() : cellPPr.addNewSpacing();
                    if (tmpSpacing.getAfter() != null) {
                        cellSpacing.setAfter(tmpSpacing.getAfter());
                    }
                    if (tmpSpacing.getAfterAutospacing() != null) {
                        cellSpacing.setAfterAutospacing(tmpSpacing.getAfterAutospacing());
                    }
                    if (tmpSpacing.getAfterLines() != null) {
                        cellSpacing.setAfterLines(tmpSpacing.getAfterLines());
                    }
                    if (tmpSpacing.getBefore() != null) {
                        cellSpacing.setBefore(tmpSpacing.getBefore());
                    }
                    if (tmpSpacing.getBeforeAutospacing() != null) {
                        cellSpacing.setBeforeAutospacing(tmpSpacing.getBeforeAutospacing());
                    }
                    if (tmpSpacing.getBeforeLines() != null) {
                        cellSpacing.setBeforeLines(tmpSpacing.getBeforeLines());
                    }
                    if (tmpSpacing.getLine() != null) {
                        cellSpacing.setLine(tmpSpacing.getLine());
                    }
                    if (tmpSpacing.getLineRule() != null) {
                        cellSpacing.setLineRule(tmpSpacing.getLineRule());
                    }
                }
                //复制段落缩进信息
                CTInd tmpInd = tmpPPr.getInd();
                if (tmpInd != null) {
                    CTInd cellInd = cellPPr.getInd() != null ? cellPPr.getInd() : cellPPr.addNewInd();
                    if (tmpInd.getFirstLine() != null) {
                        cellInd.setFirstLine(tmpInd.getFirstLine());
                    }
                    if (tmpInd.getFirstLineChars() != null) {
                        cellInd.setFirstLineChars(tmpInd.getFirstLineChars());
                    }
                    if (tmpInd.getHanging() != null) {
                        cellInd.setHanging(tmpInd.getHanging());
                    }
                    if (tmpInd.getHangingChars() != null) {
                        cellInd.setHangingChars(tmpInd.getHangingChars());
                    }
                    if (tmpInd.getLeft() != null) {
                        cellInd.setLeft(tmpInd.getLeft());
                    }
                    if (tmpInd.getLeftChars() != null) {
                        cellInd.setLeftChars(tmpInd.getLeftChars());
                    }
                    if (tmpInd.getRight() != null) {
                        cellInd.setRight(tmpInd.getRight());
                    }
                    if (tmpInd.getRightChars() != null) {
                        cellInd.setRightChars(tmpInd.getRightChars());
                    }
                }
            }
        }
    }

    /**
     * 添加图片
     * 
     * @author JueYue
     *  2013-11-20
     * @param obj
     * @param currentRun
     * @throws Exception
     */
    private static void addAnImage(ImageEntity obj, XWPFRun currentRun) throws Exception {
        Object[] isAndType = PoiPublicUtil.getIsAndType(obj);
        String picId;
        try {
            picId = currentRun.getDocument().addPictureData((byte[]) isAndType[0],
                (Integer) isAndType[1]);
            ((MyXWPFDocument) currentRun.getDocument()).createPicture(currentRun,
                picId, currentRun.getDocument()
                    .getNextPicNameNumber((Integer) isAndType[1]),
                obj.getWidth(), obj.getHeight());

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

你可能感兴趣的:(Java-Web,POI,EasyPOI)