poi+java在word指定位置生成简单表格

poi+java在word指定位置生成简单表格

    • pom.xml
    • 工具类
    • 调用
      • 模板
      • 效果

pom.xml

    
        org.apache.poi
        poi
        3.17
    
    
    
        org.apache.poi
        poi-ooxml
        3.17
    
    
    
        org.apache.poi
        poi-ooxml-schemas
        3.17
    
    
        org.apache.poi
        poi-excelant
        3.17
    
    
        org.apache.poi
        poi-scratchpad
        3.17
    

工具类

package com.example.demo2.utils;

import org.apache.poi.POIXMLDocument;
import org.apache.poi.xwpf.usermodel.*;
import org.apache.xmlbeans.XmlCursor;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigInteger;
import java.util.List;

public class InsertExcelByKeyInWord {
    //创建一个表格插入到key标记的位置
    public <T>void exportBg(List<String> head,List<T> data,String srcPath,String targetPath,String key) {
        XWPFDocument doc = null;
        try {
            doc = new XWPFDocument(POIXMLDocument.openPackage(srcPath));
            List<XWPFParagraph> paragraphList = doc.getParagraphs();
            if (paragraphList != null && paragraphList.size() > 0) {
                for (XWPFParagraph paragraph : paragraphList) {
                    List<XWPFRun> runs = paragraph.getRuns();
                    for (int i = 0; i < runs.size(); i++) {
                        String text = runs.get(i).getText(0);
                        if (text != null) {
                            text = text.trim();
                            if (text.indexOf(key) >= 0) {
                                runs.get(i).setText(text.replace(key, ""), 0);
                                XmlCursor cursor = paragraph.getCTP().newCursor();
                                // 在指定游标位置插入表格
                                XWPFTable table = doc.insertNewTbl(cursor);

                                CTTblPr tablePr = table.getCTTbl().getTblPr();
                                CTTblWidth width = tablePr.addNewTblW();
                                width.setW(BigInteger.valueOf(10500));

                                this.insertInfo(table,head,data);
                                break;
                            }
                        }
                    }
                }
            }
            FileOutputStream os = new FileOutputStream(targetPath);
            doc.write(os);
            os.flush();
            os.close();
        } catch (IOException | IllegalAccessException | IntrospectionException | InvocationTargetException e) {
            e.printStackTrace();
        }


    }

    /**
     * 把信息插入表格
     *
     */
    private <T>void insertInfo(XWPFTable table, List<String> head, List<T> data) throws IntrospectionException, InvocationTargetException, IllegalAccessException {
        //获取第一行
        XWPFTableRow row = table.getRow(0);
        //获取这个东西用来改表格宽度
        CTTblPr tblPr = table.getCTTbl().getTblPr();
        //改变长度策略为自己调整 默认为auto
        tblPr.getTblW().setType(STTblWidth.DXA);
        //设置表格宽度为7000
        tblPr.getTblW().setW(BigInteger.valueOf(10500));
        //根据头创建表格head
        for (int col = 1; col < head.size(); col++) {//默认会创建一列,即从第2列开始
            // 第一行创建了多少列,后续增加的行自动增加列
            CTTcPr cPr = row.createCell().getCTTc().addNewTcPr();
            //设置单元格高度为500
            row.getCtRow().addNewTrPr().addNewTrHeight().setVal(BigInteger.valueOf(500));
            //可以用来设置单元格长度
            //CTTblWidth width = cPr.addNewTcW();
            //width.setW(BigInteger.valueOf(2000));
        }
        //循环给表格添加头信息
        for (int i = 0; i < head.size(); i++) {
            //往表格里面写入头信息
            row.getCell(i).setText(head.get(i));
        }
        //计数器
        int i=0;
        //循环填充body列表(列表为vo数组)
        for (T item : data) {
            //获取类
            Class<?> clazz = item.getClass();
            //获取item字段
            Field[] fields = item.getClass().getDeclaredFields();
            //创建行
            row = table.createRow();
            //修改行高为500
            row.getCtRow().addNewTrPr().addNewTrHeight().setVal(BigInteger.valueOf(500));
            //循环获取vo类的属性
            for (Field field : fields) {
                //获取当前field的属性描述器
                PropertyDescriptor descriptor = new PropertyDescriptor(field.getName(), clazz);
                //获取field字段的get方法
                Method readMethod = descriptor.getReadMethod();
                //执行get方法并填充到表格中
                row.getCell(i).setText(String.valueOf(readMethod.invoke(item)));
                //计数器+1
                i++;
            }
            //执行完一行计数器归零
            i=0;
        }
    }

}

调用

@Test
    void contextLoads() {
        System.out.println("hello world");
        InsertExcelByKeyInWord insertExcelByKeyInWord =new InsertExcelByKeyInWord();
        List<Person> dtos=new ArrayList<>();
        for (int i = 0; i <20 ; i++) {
            Person dto=new Person("张三",22,"男");
            dtos.add(dto);
        }
        List<String> head=new ArrayList<>();
        head.add("姓名");
        head.add("年龄");
        head.add("性别");
        String srcPath = "F:/模板地址.docx";
        String targetPath = "F:/文件地址.docx";
        String key = "$key";// 在文档中需要替换插入表格的位置
        insertExcelByKeyInWord.exportBg(head,dtos,srcPath,targetPath,key);
    }

模板

如果你想尝试使用此编辑器, 你可以在此篇文章任意编辑。当你完成了一篇文章的写作, 在上方工具栏找到 **文章导出** ,生成一个.md文件或者.html文件进行本地保存。

效果

poi+java在word指定位置生成简单表格_第1张图片

你可能感兴趣的:(poi+java在word指定位置生成简单表格)