Poi实现根据word模板导出-表格篇

往期系列传送门:

Poi实现根据word模板导出-文本段落篇

Poi实现根据word模板导出-图表篇

(需要完整代码的直接看最后位置!!!)

前言:

word中表格数据填充是非常简单的,非常类似excel。如果你是从之前系列看过来的,应该能想到思路应该也是通过poi获取表格对象,然后通过表格对象操作里面的内容,套路都是一样的。

话不多说,直接看代码吧,这部分很简单:

@RequestMapping("/export")
public void exportWord() throws Exception {
    //获取word模板
    InputStream is = WordController.class.getResourceAsStream("/template/wordChartTemplate.docx");

    try {
        ZipSecureFile.setMinInflateRatio(-1.0d);
        // 获取docx解析对象
        XWPFDocument document = new XWPFDocument(is);
        // 填充表格数据
        changeTable(document);
        // 输出新文件
        FileOutputStream fos = new FileOutputStream("D:\\test\\test.docx");
        document.write(fos);
        document.close();
        fos.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

private void changeTable(XWPFDocument document) {
    // 获取文档第一个表格(有几个就按顺序取)
    XWPFTable table = document.getTables().get(0);
    // 填充表格数据
    // 获取表格行数
    int numberOfRows = table.getNumberOfRows();
    for (int i = 0; i < numberOfRows; i++) {
        // 获取当前行
        XWPFTableRow row = table.getRow(i);
        // 变量循环当前行,获取单元格
        for (int j = 0; j < row.getTableCells().size(); j++) {
            // 获取当前单元格
            XWPFTableCell cell = row.getCell(j);
            if (null == cell) {
                cell = row.createCell();
            }
            // 填充单元格数据
            cell.setText("A" + i + "," + j);
        }
    }
}

效果实现:每个表格都有自己的坐标,和Excel基本一样。行列坐标都是从0开始

Poi实现根据word模板导出-表格篇_第1张图片

补充:

整个poi操作word都是基于以下maven依赖


    org.apache.poi
    poi-ooxml
    4.1.2


    org.apache.poi
    poi
    4.1.2



    com.deepoove
    poi-tl
    1.12.0
    
        
        
            org.apache.poi
            poi-ooxml
        
    

你可能感兴趣的:(POI系列,java,word)