java导出word文档

这段代码展示了如何使用Apache POI库在Java中创建和操作Word文档,包括创建标题、段落、表格,设置文本样式,合并单元格,以及保存文档。此外,还定义了ParagraphStyle和TextStyle类来存储段落和文本的样式信息,并提供了工具类XWPFHelper和XWPFHelperTable来辅助设置文档样式和操作表格。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

导出word文档

导入的jar

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>3.17</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.17</version>
</dependency>

导出word文档

public class ExportWord {
	private XWPFHelperTable xwpfHelperTable = null;    
    private XWPFHelper xwpfHelper = null;
    public ExportWord() {
        xwpfHelperTable = new XWPFHelperTable();
        xwpfHelper = new XWPFHelper();
    }
    /**
     * 创建好文档的基本 标题,表格  段落等部分
     * @param text 
     * @return
     */
    public XWPFDocument createXWPFDocument(String text) {
        XWPFDocument doc = new XWPFDocument();
        createTitleParagraph(doc);
        createTextParagraph(doc,text);
        createTableParagraph(doc, 12, 4);
        createBreakParagraph(doc);
        return doc;
    }
    /**
     * 创建表格的标题样式
     * @param document
     */
    public void createTitleParagraph(XWPFDocument document) {
        XWPFParagraph titleParagraph = document.createParagraph();    //新建一个标题段落对象(就是一段文字)
        titleParagraph.setAlignment(ParagraphAlignment.CENTER);//样式居中
        XWPFRun titleFun = titleParagraph.createRun();    //创建文本对象
//        titleFun.setText(titleName); //设置标题的名字
        titleFun.setBold(true); //加粗
        titleFun.setColor("000000");//设置颜色
        titleFun.setFontSize(25);    //字体大小
//        titleFun.setFontFamily("");//设置字体
        //...
        titleFun.addBreak();    //换行
    }
    
    /**
     * 创建表格的标题样式
     * @param document
     */
    public void createTextParagraph(XWPFDocument document,String text) {
        XWPFParagraph titleParagraph = document.createParagraph();    //新建一个标题段落对象(就是一段文字)
        titleParagraph.setAlignment(ParagraphAlignment.LEFT);//样式居中
        XWPFRun titleFun = titleParagraph.createRun();    //创建文本对象
       titleFun.setText(text); //设置标题的名字
        titleFun.setColor("000000");//设置颜色
        titleFun.setFontSize(8);    //字体大小
        titleFun.addBreak();    //换行
    }
    
    /**
     * 创建表格的标题样式
     * @param document
     */
    public void createBreakParagraph(XWPFDocument document) {
        XWPFParagraph titleParagraph = document.createParagraph();    //新建一个标题段落对象(就是一段文字)
        titleParagraph.setAlignment(ParagraphAlignment.RIGHT);//样式居中
        XWPFRun titleFun = titleParagraph.createRun();    //创建文本对象
        SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
        titleFun.setText("办理时间:"+dateformat.format(new Date())); //设置标题的名字
        titleFun.setBold(true); //加粗
        titleFun.setColor("000000");//设置颜色
        titleFun.setFontSize(12);    //字体大小
//        titleFun.setFontFamily("");//设置字体
        //...
        titleFun.addBreak();    //换行
    }
    /**
     * 设置表格
     * @param document
     * @param rows
     * @param cols
     */
    public void createTableParagraph(XWPFDocument document, int rows, int cols) {
//        xwpfHelperTable.createTable(xdoc, rowSize, cellSize, isSetColWidth, colWidths)
        XWPFTable infoTable = document.createTable(rows, cols);
        xwpfHelperTable.setTableWidthAndHAlign(infoTable, "9072", STJc.CENTER);
        //合并表格
        xwpfHelperTable.mergeCellsHorizontal(infoTable, 6, 1, 3);
        xwpfHelperTable.mergeCellsVertically(infoTable, 0, 5, 6);
        xwpfHelperTable.mergeCellsVertically(infoTable, 0, 7, 8);
        for(int col = 5; col < 10; col++) {
            xwpfHelperTable.mergeCellsHorizontal(infoTable, col, 0, 3);
        }
        //设置表格样式
        List<XWPFTableRow> rowList = infoTable.getRows();
        for(int i = 0; i < rowList.size(); i++) {
            XWPFTableRow infoTableRow = rowList.get(i);
            List<XWPFTableCell> cellList = infoTableRow.getTableCells();
            for(int j = 0; j < cellList.size(); j++) {
                XWPFParagraph cellParagraph = cellList.get(j).getParagraphs().get(0);
                cellParagraph.setAlignment(ParagraphAlignment.CENTER);
                XWPFRun cellParagraphRun = cellParagraph.createRun();
                cellParagraphRun.setFontSize(12);
                cellParagraphRun.setBold(true);
            }
        }
        xwpfHelperTable.setTableHeight(infoTable, 560, STVerticalJc.CENTER);
    }
    
    /**
     * 往表格中填充数据
     * @param dataList
     * @param document
     * @throws IOException
     */
    @SuppressWarnings("unchecked")
    public void exportCheckWord(Map<String, Object> dataList, XWPFDocument document, String savePath) throws IOException {
        XWPFParagraph paragraph = document.getParagraphs().get(0);
        XWPFRun titleFun = paragraph.getRuns().get(0);
        titleFun.setText(String.valueOf(dataList.get("TITLE")));
        List<List<Object>> tableData = (List<List<Object>>) dataList.get("TABLEDATA");
        XWPFTable table = document.getTables().get(0);
        fillTableData(table, tableData);
        xwpfHelper.saveDocument(document, savePath);
    }
    /**
     * 往表格中填充数据
     * @param table
     * @param tableData
     */
    public void fillTableData(XWPFTable table, List<List<Object>> tableData) {
        List<XWPFTableRow> rowList = table.getRows();
        for(int i = 0; i < tableData.size(); i++) {
            List<Object> list = tableData.get(i);
            List<XWPFTableCell> cellList = rowList.get(i).getTableCells();
            for(int j = 0; j < list.size(); j++) {
                XWPFParagraph cellParagraph = cellList.get(j).getParagraphs().get(0);
                XWPFRun cellParagraphRun = cellParagraph.getRuns().get(0);
                cellParagraphRun.setText(String.valueOf(list.get(j)));
            }
        }
    }
}
``

实体类

public class ParagraphStyle {
	private boolean isSpace;  //是否缩进
    private String before;      //段前磅数
    private String after;  //段后磅数
    private String beforeLines;        //段前行数
    private String afterLines;        //段后行数
    private boolean isLine;        //是否间距
    private String line;    //间距距离
    //段落缩进信息
    private String firstLine;
    private String firstLineChar;
    private String hanging;
    private String hangingChar;
    private String right;
    private String rightChar;
    private String left;
    private String leftChar;
	public boolean isSpace() {
		return isSpace;
	}
	public void setSpace(boolean isSpace) {
		this.isSpace = isSpace;
	}
	public String getBefore() {
		return before;
	}
	public void setBefore(String before) {
		this.before = before;
	}
	public String getAfter() {
		return after;
	}
	public void setAfter(String after) {
		this.after = after;
	}
	public String getBeforeLines() {
		return beforeLines;
	}
	public void setBeforeLines(String beforeLines) {
		this.beforeLines = beforeLines;
	}
	public String getAfterLines() {
		return afterLines;
	}
	public void setAfterLines(String afterLines) {
		this.afterLines = afterLines;
	}
	public boolean isLine() {
		return isLine;
	}
	public void setLine(boolean isLine) {
		this.isLine = isLine;
	}
	public String getLine() {
		return line;
	}
	public void setLine(String line) {
		this.line = line;
	}
	public String getFirstLine() {
		return firstLine;
	}
	public void setFirstLine(String firstLine) {
		this.firstLine = firstLine;
	}
	public String getFirstLineChar() {
		return firstLineChar;
	}
	public void setFirstLineChar(String firstLineChar) {
		this.firstLineChar = firstLineChar;
	}
	public String getHanging() {
		return hanging;
	}
	public void setHanging(String hanging) {
		this.hanging = hanging;
	}
	public String getHangingChar() {
		return hangingChar;
	}
	public void setHangingChar(String hangingChar) {
		this.hangingChar = hangingChar;
	}
	public String getRight() {
		return right;
	}
	public void setRight(String right) {
		this.right = right;
	}
	public String getRightChar() {
		return rightChar;
	}
	public void setRightChar(String rightChar) {
		this.rightChar = rightChar;
	}
	public String getLeft() {
		return left;
	}
	public void setLeft(String left) {
		this.left = left;
	}
	public String getLeftChar() {
		return leftChar;
	}
	public void setLeftChar(String leftChar) {
		this.leftChar = leftChar;
	}
    
}

public class TextStyle {
	private String url;    // 超链接
    private String text;    //文本内容
    private String fontFamily;    //字体
    private String fontSize;    //字体大小
    private String colorVal;    //字体颜色
    private String shdColor;    //底纹颜色
    private int position;    //文本位置
    private int spacingValue;    //间距
    private int indent;    //缩进
    private boolean isBlod;    //加粗
    private boolean isUnderLine;    //下划线
    private boolean underLineColor;    //
    private boolean isItalic;    //倾斜
    private boolean isStrike;    //删除线
    private boolean isDStrike;    //双删除线
    private boolean isShadow;    //阴影
    private boolean isVanish;    //隐藏
    private boolean isEmboss;    //阳文
    private boolean isImprint;    //阴文
    private boolean isOutline;    //空心
    private boolean isHightLight;    //突出显示文本
    private boolean isShd;    //底纹
	public String getUrl() {
		return url;
	}
	public void setUrl(String url) {
		this.url = url;
	}
	public String getText() {
		return text;
	}
	public void setText(String text) {
		this.text = text;
	}
	public String getFontFamily() {
		return fontFamily;
	}
	public void setFontFamily(String fontFamily) {
		this.fontFamily = fontFamily;
	}
	public String getFontSize() {
		return fontSize;
	}
	public void setFontSize(String fontSize) {
		this.fontSize = fontSize;
	}
	public String getColorVal() {
		return colorVal;
	}
	public void setColorVal(String colorVal) {
		this.colorVal = colorVal;
	}
	public String getShdColor() {
		return shdColor;
	}
	public void setShdColor(String shdColor) {
		this.shdColor = shdColor;
	}
	public int getPosition() {
		return position;
	}
	public void setPosition(int position) {
		this.position = position;
	}
	public int getSpacingValue() {
		return spacingValue;
	}
	public void setSpacingValue(int spacingValue) {
		this.spacingValue = spacingValue;
	}
	public int getIndent() {
		return indent;
	}
	public void setIndent(int indent) {
		this.indent = indent;
	}
	public boolean isBlod() {
		return isBlod;
	}
	public void setBlod(boolean isBlod) {
		this.isBlod = isBlod;
	}
	public boolean isUnderLine() {
		return isUnderLine;
	}
	public void setUnderLine(boolean isUnderLine) {
		this.isUnderLine = isUnderLine;
	}
	public boolean isUnderLineColor() {
		return underLineColor;
	}
	public void setUnderLineColor(boolean underLineColor) {
		this.underLineColor = underLineColor;
	}
	public boolean isItalic() {
		return isItalic;
	}
	public void setItalic(boolean isItalic) {
		this.isItalic = isItalic;
	}
	public boolean isStrike() {
		return isStrike;
	}
	public void setStrike(boolean isStrike) {
		this.isStrike = isStrike;
	}
	public boolean isDStrike() {
		return isDStrike;
	}
	public void setDStrike(boolean isDStrike) {
		this.isDStrike = isDStrike;
	}
	public boolean isShadow() {
		return isShadow;
	}
	public void setShadow(boolean isShadow) {
		this.isShadow = isShadow;
	}
	public boolean isVanish() {
		return isVanish;
	}
	public void setVanish(boolean isVanish) {
		this.isVanish = isVanish;
	}
	public boolean isEmboss() {
		return isEmboss;
	}
	public void setEmboss(boolean isEmboss) {
		this.isEmboss = isEmboss;
	}
	public boolean isImprint() {
		return isImprint;
	}
	public void setImprint(boolean isImprint) {
		this.isImprint = isImprint;
	}
	public boolean isOutline() {
		return isOutline;
	}
	public void setOutline(boolean isOutline) {
		this.isOutline = isOutline;
	}
	public boolean isHightLight() {
		return isHightLight;
	}
	public void setHightLight(boolean isHightLight) {
		this.isHightLight = isHightLight;
	}
	public boolean isShd() {
		return isShd;
	}
	public void setShd(boolean isShd) {
		this.isShd = isShd;
	}
    
}

工具类

/**
 * @Description 设置docx文档的样式及一些操作  
 * @Author  yinwenjie
 * 基本概念说明:XWPFDocument代表一个docx文档,其可以用来读docx文档,也可以用来写docx文档
 *     XWPFParagraph代表文档、表格、标题等种的段落,由多个XWPFRun组成
 *     XWPFRun代表具有同样风格的一段文本
 *  XWPFTable代表一个表格
 *  XWPFTableRow代表表格的一行
 *  XWPFTableCell代表表格的一个单元格    
 *  XWPFChar 表示.docx文件中的图表
 *  XWPFHyperlink 表示超链接
 *  XWPFPicture  代表图片
 *  
 *  注意:直接调用XWPFRun的setText()方法设置文本时,在底层会重新创建一个XWPFRun。
 */
public class XWPFHelper {
    private static Logger logger = Logger.getLogger(XWPFHelper.class.toString());
    
    /**
     * 创建一个word对象
     * @return
     */
    public XWPFDocument createDocument() {
        XWPFDocument document = new XWPFDocument();
        return document;
    }
    /**
     * 打开word文档
     * @param path 文档所在路径
     * @return
     * @throws IOException
     */
    public XWPFDocument openDoc(String path) throws IOException {
        InputStream is = new FileInputStream(path);
        return new XWPFDocument(is);
    }
    /**
     * 保存word文档
     * @param document 文档对象
     * @param savePath    保存路径
     * @throws IOException
     */
    public void saveDocument(XWPFDocument document, String savePath) throws IOException {
        OutputStream os = new FileOutputStream(savePath);
        document.write(os);
        os.close();
    }
    /**
     * 设置段落文本样式  设置超链接及样式
     * @param paragraph
     * @param textStyle
     * @param url
     */
    public void addParagraphTextHyperlink(XWPFParagraph paragraph, TextStyle textStyle) {
        String id = paragraph.getDocument().getPackagePart().
            addExternalRelationship(textStyle.getUrl(),
                XWPFRelation.HYPERLINK.getRelation()).getId();
        //追加链接并将其绑定到关系中
        CTHyperlink cLink = paragraph.getCTP().addNewHyperlink();
        cLink.setId(id);
        //创建链接文本
        CTText ctText = CTText.Factory.newInstance();
        ctText.setStringValue(textStyle.getText());
        CTR ctr = CTR.Factory.newInstance();
        CTRPr rpr = ctr.addNewRPr();
        //以下设置各种样式 详情看TextStyle类
        if(textStyle.getFontFamily() != "" && textStyle.getFontFamily() != null     ) {
            CTFonts fonts = rpr.isSetRFonts() ? rpr.getRFonts() : rpr.addNewRFonts();
            fonts.setAscii(textStyle.getFontFamily());
            //...
        }
        //设置字体大小
    }
    /**
     * 设置段落的基本样式  设置段落间距信息, 一行 = 100    一磅=20 
     * @param paragraph
     * @param paragStyle
     */
    public void setParagraphSpacingInfo(XWPFParagraph paragraph, ParagraphStyle paragStyle, STLineSpacingRule.Enum lineValue) {
        CTPPr pPPr = getParagraphCTPPr(paragraph);
        CTSpacing pSpacing = pPPr.getSpacing() != null ? pPPr.getSpacing() : pPPr.addNewSpacing();
        if(paragStyle.isSpace()) {
            //段前磅数
            if(paragStyle.getBefore() != null) {
                pSpacing.setBefore(new BigInteger(paragStyle.getBefore()));
            }
            //段后磅数
            if(paragStyle.getAfter() != null) {
                pSpacing.setAfter(new BigInteger(paragStyle.getAfter()));
            }
            //依次设置段前行数、段后行数
            //...
        }
        //间距
        if(paragStyle.isLine()) {
            if(paragStyle.getLine() != null) {
                pSpacing.setLine(new BigInteger(paragStyle.getLine()));
            }
            if(lineValue != null) {
                pSpacing.setLineRule(lineValue);    //
            }
        }
    }
    /**
 * 设置段落缩进信息  1厘米 约等于 567
     * @param paragraph
     * @param paragStyle
     */
    public void setParagraphIndInfo(XWPFParagraph paragraph, ParagraphStyle paragStyle) {
        CTPPr pPPr = getParagraphCTPPr(paragraph);
        CTInd pInd = pPPr.getInd() != null ? pPPr.getInd() : pPPr.addNewInd();
        if(paragStyle.getFirstLine() != null) {
            pInd.setFirstLine(new BigInteger(paragStyle.getFirstLine()));
        }
        //再进行其他设置
        //...
    }
    /**
     * 设置段落对齐 方式
     * @param paragraph
     * @param pAlign
     * @param valign
     */
    public void setParagraphAlignInfo(XWPFParagraph paragraph, ParagraphAlignment pAlign, TextAlignment valign) {
        if(pAlign != null) {
            paragraph.setAlignment(pAlign);
        }
        if(valign != null) {
            paragraph.setVerticalAlignment(valign);
        }
    }
    /**
     * 得到段落的CTPPr
     * @param paragraph
     * @return
     */
    public CTPPr getParagraphCTPPr(XWPFParagraph paragraph) {
        CTPPr pPPr = null;
        if(paragraph.getCTP() != null) {
            if(paragraph.getCTP().getPPr() != null) {
                pPPr = paragraph.getCTP().getPPr();
            } else {
                pPPr = paragraph.getCTP().addNewPPr();
            }
        }
        return pPPr;
    }
    /**
     * 得到XWPFRun的CTRPr
     * @param paragraph
     * @param pRun
     * @return
     */
    public CTRPr getRunCTRPr(XWPFParagraph paragraph, XWPFRun pRun) {
        CTRPr ctrPr = null;
        if(pRun.getCTR() != null) {
            ctrPr = pRun.getCTR().getRPr();
            if(ctrPr == null) {
                ctrPr = pRun.getCTR().addNewRPr();
            }
        } else {
            ctrPr = paragraph.getCTP().addNewR().addNewRPr();
        }
        return ctrPr;
    }
    
    
    /**
     * 复制表格
     * @param targetTable
     * @param sourceTable
     */
    public void copyTable(XWPFTable targetTable, XWPFTable sourceTable) {
        //复制表格属性
        targetTable.getCTTbl().setTblPr(sourceTable.getCTTbl().getTblPr());
        //复制行
        for(int i = 0; i < sourceTable.getRows().size(); i++) {
            XWPFTableRow targetRow = targetTable.getRow(i);
            XWPFTableRow sourceRow = sourceTable.getRow(i);
            if(targetRow == null) {
                targetTable.addRow(sourceRow);
            } else {
                copyTableRow(targetRow, sourceRow);
            }
        }
    }
    /**
     * 复制单元格
     * @param targetRow
     * @param sourceRow
     */
    public void copyTableRow(XWPFTableRow targetRow, XWPFTableRow sourceRow) {
        //复制样式
        if(sourceRow != null) {
            targetRow.getCtRow().setTrPr(sourceRow.getCtRow().getTrPr());
        }
        //复制单元格
        for(int i = 0; i < sourceRow.getTableCells().size(); i++) {
            XWPFTableCell tCell = targetRow.getCell(i);
            XWPFTableCell sCell = sourceRow.getCell(i);
            if(tCell == sCell) {
                tCell = targetRow.addNewTableCell();
            }
            copyTableCell(tCell, sCell);
        }
    }
    /**
     * 复制单元格(列) 从sourceCell到targetCell
     * @param targetCell
     * @param sourceCell
     */
    public void copyTableCell(XWPFTableCell targetCell, XWPFTableCell sourceCell) {
        //表格属性
        if(sourceCell.getCTTc() != null) {
            targetCell.getCTTc().setTcPr(sourceCell.getCTTc().getTcPr());
        }
        //删除段落
        for(int pos = 0; pos < targetCell.getParagraphs().size(); pos++) {
            targetCell.removeParagraph(pos);
        }
        //添加段落
        for(XWPFParagraph sourceParag : sourceCell.getParagraphs()) {
            XWPFParagraph targetParag = targetCell.addParagraph();
            copyParagraph(targetParag, sourceParag);
        }
    }
    /**
     * 复制段落,从sourceParag到targetParag
     * @param targetParag
     * @param sourceParag
     */
    public void copyParagraph(XWPFParagraph targetParag, XWPFParagraph sourceParag) {
        targetParag.getCTP().setPPr(sourceParag.getCTP().getPPr());    //设置段落样式
        //移除所有的run
        for(int pos = targetParag.getRuns().size() - 1; pos >= 0; pos-- ) {
            targetParag.removeRun(pos);
        }
        //copy新的run
        for(XWPFRun sRun : sourceParag.getRuns()) {
            XWPFRun tarRun = targetParag.createRun();
            copyRun(tarRun, sRun);
        }
    }
    /**
     * 复制XWPFRun 从sourceRun到targetRun
     * @param targetRun
     * @param sourceRun
     */
    public void copyRun(XWPFRun targetRun, XWPFRun sourceRun) {
        //设置targetRun属性
        targetRun.getCTR().setRPr(sourceRun.getCTR().getRPr());
        targetRun.setText(sourceRun.getText(1));//设置文本
        //处理图片
        List<XWPFPicture> pictures = sourceRun.getEmbeddedPictures();
        for(XWPFPicture picture : pictures) {
            try {
                copyPicture(targetRun, picture);
            } catch (InvalidFormatException e) {
                e.printStackTrace();
                logger.log(Level.WARNING, "copyRun", e);
            } catch (IOException e) {
                e.printStackTrace();
                logger.log(Level.WARNING, "copyRun", e);
            }
        }
    }
    /**
     * 复制图片从sourcePicture到 targetRun(XWPFPicture --> XWPFRun)
     * @param targetRun
     * @param source
     * @throws IOException 
     * @throws InvalidFormatException 
     */
    public void copyPicture(XWPFRun targetRun, XWPFPicture sourcePicture) throws InvalidFormatException, IOException {
        XWPFPictureData picData = sourcePicture.getPictureData();
        String fileName = picData.getFileName();    //图片的名称
        InputStream picInIsData = new ByteArrayInputStream(picData.getData());    
        int picType = picData.getPictureType();
        int width = (int) sourcePicture.getCTPicture().getSpPr().getXfrm().getExt().getCx();
        int height =  (int) sourcePicture.getCTPicture().getSpPr().getXfrm().getExt().getCy();
        targetRun.addPicture(picInIsData, picType, fileName, width, height);
//        targetRun.addBreak();//分行
    }
}


工具类二

/**
 * @Description 操作word的基本工具类
 * 2018年12月3日  上午11:12:18
 */
public class XWPFHelperTable {
    
    /**
     * 删除指定位置的表格,被删除表格后的索引位置
     * @param document
     * @param pos
     */
    public void deleteTableByIndex(XWPFDocument document, int pos) {
        Iterator<IBodyElement> bodyElement = document.getBodyElementsIterator();
        int eIndex = 0, tableIndex = -1;
        while(bodyElement.hasNext()) {
            IBodyElement element = bodyElement.next();
            BodyElementType elementType = element.getElementType();
            if(elementType == BodyElementType.TABLE) {
                tableIndex++;
                if(tableIndex == pos) {
                    break;
                }
            }
            eIndex++;
        }
        document.removeBodyElement(eIndex);
    }
    /**
     * 获得指定位置的表格
     * @param document
     * @param index
     * @return
     */
    public XWPFTable getTableByIndex(XWPFDocument document, int index) {
        List<XWPFTable> tableList = document.getTables();
        if(tableList == null || index < 0 || index > tableList.size()) {
            return null;
        }
        return tableList.get(index);
    }
    /**
     * 得到表格的内容(第一次跨行单元格视为一个,第二次跳过跨行合并的单元格)
     * @param table
     * @return
     */
    public List<List<String>> getTableRConten(XWPFTable table) {
        List<List<String>> tableContextList = new ArrayList<List<String>>();
        for(int rowIndex = 0, rowLen = table.getNumberOfRows(); rowIndex < rowLen; rowIndex++) {
            XWPFTableRow row = table.getRow(rowIndex);
            List<String> cellContentList = new ArrayList<String>();
            for(int colIndex = 0, colLen = row.getTableCells().size(); colIndex < colLen; colIndex++ ) {
                XWPFTableCell cell = row.getCell(colIndex);
                CTTc ctTc = cell.getCTTc();
                if(ctTc.isSetTcPr()) {
                    CTTcPr tcPr = ctTc.getTcPr();
                    if(tcPr.isSetHMerge()) {
                        CTHMerge hMerge = tcPr.getHMerge();
                        if(STMerge.RESTART.equals(hMerge.getVal())) {
                            cellContentList.add(getTableCellContent(cell));
                        }
                    } else if(tcPr.isSetVMerge()) {
                        CTVMerge vMerge = tcPr.getVMerge();
                        if(STMerge.RESTART.equals(vMerge.getVal())) {
                            cellContentList.add(getTableCellContent(cell));
                        }
                    } else {
                        cellContentList.add(getTableCellContent(cell));
                    }
                }
            }
            tableContextList.add(cellContentList);
        }
        return tableContextList;
    }

    /**
     * 获得一个表格的单元格的内容
     * @param cell
     * @return
     */
    public String getTableCellContent(XWPFTableCell cell) {
        StringBuffer sb = new StringBuffer();
        List<XWPFParagraph> cellParagList = cell.getParagraphs();
        if(cellParagList != null && cellParagList.size() > 0) {
            for(XWPFParagraph xwpfPr: cellParagList) {
                List<XWPFRun> runs = xwpfPr.getRuns();
                if(runs != null && runs.size() > 0) {
                    for(XWPFRun xwpfRun : runs) {
                        sb.append(xwpfRun.getText(0));
                    }
                }
            }
        }
        return sb.toString();
    }
    /**
     * 得到表格内容,合并后的单元格视为一个单元格
     * @param table
     * @return
     */
    public List<List<String>> getTableContent(XWPFTable table) {
       List<List<String>> tableContentList = new ArrayList<List<String>>();
        for (int rowIndex = 0, rowLen = table.getNumberOfRows(); rowIndex < rowLen; rowIndex++) {
          XWPFTableRow row = table.getRow(rowIndex);
          List<String> cellContentList = new ArrayList<String>();
          for (int colIndex = 0, colLen = row.getTableCells().size(); colIndex < colLen; colIndex++) {
            XWPFTableCell cell = row.getCell(colIndex);
            cellContentList.add(getTableCellContent(cell));
          }
          tableContentList.add(cellContentList);
        }
        return tableContentList;
    }
    
    /**
     * 跨列合并
     * @param table
     * @param row    所合并的行
     * @param fromCell    起始列
     * @param toCell    终止列
     * @Description
     */
    public void mergeCellsHorizontal(XWPFTable table, int row, int fromCell, int toCell) {
        for(int cellIndex = fromCell; cellIndex <= toCell; cellIndex++ ) {
            XWPFTableCell cell = table.getRow(row).getCell(cellIndex);
            if(cellIndex == fromCell) {
                cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART);
            } else {
                cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE);
            }
        }
    }
    /**
     * 跨行合并
     * @param table
     * @param col    合并的列
     * @param fromRow    起始行
     * @param toRow    终止行
     * @Description
     */
    public void mergeCellsVertically(XWPFTable table, int col, int fromRow, int toRow) {
        for(int rowIndex = fromRow; rowIndex <= toRow; rowIndex++) {
            XWPFTableCell cell = table.getRow(rowIndex).getCell(col);
            //第一个合并单元格用重启合并值设置
            if(rowIndex == fromRow) {
                cell.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.RESTART);
            } else {
                //合并第一个单元格的单元被设置为“继续”
                cell.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.CONTINUE);
            }
        }
    }

      /**
       * @Description: 创建表格,创建后表格至少有1行1列,设置列宽
       */
      public XWPFTable createTable(XWPFDocument xdoc, int rowSize, int cellSize,
          boolean isSetColWidth, int[] colWidths) {
        XWPFTable table = xdoc.createTable(rowSize, cellSize);
        if (isSetColWidth) {
          CTTbl ttbl = table.getCTTbl();
          CTTblGrid tblGrid = ttbl.addNewTblGrid();
          for (int j = 0, len = Math.min(cellSize, colWidths.length); j < len; j++) {
              CTTblGridCol gridCol = tblGrid.addNewGridCol();
              gridCol.setW(new BigInteger(String.valueOf(colWidths[j])));
          }
        }
        return table;
      }

      /**
       * @Description: 设置表格总宽度与水平对齐方式
       */
      public void setTableWidthAndHAlign(XWPFTable table, String width,
          STJc.Enum enumValue) {
        CTTblPr tblPr = getTableCTTblPr(table);
        // 表格宽度
        CTTblWidth tblWidth = tblPr.isSetTblW() ? tblPr.getTblW() : tblPr.addNewTblW();
        if (enumValue != null) {
          CTJc cTJc = tblPr.addNewJc();
          cTJc.setVal(enumValue);
        }
        // 设置宽度
        tblWidth.setW(new BigInteger(width));
        tblWidth.setType(STTblWidth.DXA);
      }

      /**
       * @Description: 得到Table的CTTblPr,不存在则新建
       */
      public CTTblPr getTableCTTblPr(XWPFTable table) {
        CTTbl ttbl = table.getCTTbl();
        // 表格属性
        CTTblPr tblPr = ttbl.getTblPr() == null ? ttbl.addNewTblPr() : ttbl.getTblPr();
        return tblPr;
      }
    
      /**
       * 设置表格行高
       * @param infoTable
       * @param heigth 高度
       * @param vertical 表格内容的显示方式:居中、靠右...
       */
      public void setTableHeight(XWPFTable infoTable, int heigth, STVerticalJc.Enum vertical) {
        List<XWPFTableRow> rows = infoTable.getRows();
        for(XWPFTableRow row : rows) {
            CTTrPr trPr = row.getCtRow().addNewTrPr();
            CTHeight ht = trPr.addNewTrHeight();
            ht.setVal(BigInteger.valueOf(heigth));
            List<XWPFTableCell> cells = row.getTableCells();
            for(XWPFTableCell tableCell : cells ) {
                CTTcPr cttcpr = tableCell.getCTTc().addNewTcPr();
                cttcpr.addNewVAlign().setVal(vertical);
            }
        }
      }
}


测试类

public class TestExportWord {
	private static Logger logger = LoggerFactory.getLogger(TestExportWord.class);
	public static void export(String number,String name,String city,String bktype,String sex,String nation,
			String country,String zjtype,String bank,String phone,String type) {
		 ExportWord ew = new ExportWord();
	        XWPFDocument document = ew.createXWPFDocument("(一式两联 "+type+"联)");
List<List<Object>> list = new ArrayList<List<Object>>();
	        
	        List<Object> tempList = new ArrayList<Object>();
	        tempList.add("社会保障号码");
	        tempList.add(number);
	        tempList.add("姓名");
	        tempList.add(name);
	        list.add(tempList);
	        tempList = new ArrayList<Object>();
	        tempList.add("发卡城市");
	        tempList.add(city);
	        tempList.add("办卡类型");
	        tempList.add(bktype);
	        list.add(tempList);
	        tempList = new ArrayList<Object>();
	        tempList.add("性别");
	        tempList.add(sex);
	        tempList.add("民族");
	        tempList.add(nation);
	        list.add(tempList);
	        tempList = new ArrayList<Object>();
	        tempList.add("国家");
	        tempList.add(country);
	        tempList.add("证件类型");
	        tempList.add(zjtype);
	        list.add(tempList);
	        tempList = new ArrayList<Object>();
	        tempList.add("服务银行");
	        tempList.add(bank);
	        tempList.add("移动电话");
	        tempList.add(phone);
	        list.add(tempList);
	        tempList = new ArrayList<Object>();
	        tempList.add("电子社保卡同步申领告知提醒:根据电子社保卡同步申领告知确认示例,拟由各银行根据实际情况编写内容 (二代卡不填)");
	        list.add(tempList);
	        tempList = new ArrayList<Object>();
	        list.add(tempList);
	        tempList = new ArrayList<Object>();
	        tempList.add("请核对个人信息及提醒,如果没有错误请签字确认");
	        list.add(tempList);
	        tempList = new ArrayList<Object>();
	        list.add(tempList);
	        tempList = new ArrayList<Object>();
	        tempList.add("   口 申请确认                               口 启用领取确认");
	        list.add(tempList);
	        tempList = new ArrayList<Object>();
	        tempList.add("本人姓名");
	        tempList.add("");
	        tempList.add("联系电话");
	        tempList.add("");
	        list.add(tempList);
	        tempList = new ArrayList<Object>();
	        tempList.add("代办人姓名");
	        tempList.add("");
	        tempList.add("移动电话");
	        tempList.add("");
	        list.add(tempList);
	        Map<String, Object> dataList = new HashMap<String, Object>();
	        dataList.put("TITLE", "江西省社会保障卡申领确认单");
	        dataList.put("TABLEDATA", list);
	        try {
	        	File dir = new File("D:/exportWord");
				if (!dir.exists()) {// 判断目录是否存在
					dir.mkdir();
				}
	        	ew.exportCheckWord(dataList, document, "D:/exportWord/"+name+number+type+".docx");
			} catch (Exception e) {
				e.getMessage();
				logger.info("导出失败:"+e.getMessage());
			}
	}
	
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值