aspose.words填充表格数据

try {
    Document document = new Document("template.doc");
    //内容
 List list=getData();
DataTable dataTable = new DataTable("items");
Class objClass = list.get(0).getClass();
Field[] fields = objClass.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
    dataTable.getColumns().add(fields[i].getName());
}
for (Vo vo :list) {
    DataRow dataRow = dataTable.newRow();
    for (int i = 0; i < fields.length; i++) {
        Field field = fields[i];
        field.setAccessible(true);
        String value = "";
        Class type = field.getType();
        if (Date.class.equals(type)) {
            Object o = field.get(vo);
            if (o!=null){
                value = DateUtil.format((Date) field.get(vo), "yyyy年MM月dd日");
            }
        } else {
            value = field.get(vo).toString();
        }
        dataRow.set(i,value);
    }
    dataTable.getRows().add(dataRow);
}
document.getMailMerge().executeWithRegions(dataTable);
document.save("xxx.pdf");
} catch (Exception e) {
    System.out.println(e.getMessage());
}

ctr+f9编辑域

aspose.words填充表格数据_第1张图片

aspose.words填充表格数据_第2张图片

//map填充

static DataTable getDataTable(String tableName, List> list) {
    DataTable dataTable = new DataTable(tableName);
    Map map1 = list.get(0);
    Set keys = map1.keySet();
    for (String key : keys) {
        dataTable.getColumns().add(key);
    }
    for (int i = 0; i < list.size(); i++) {
        DataRow dataRow = dataTable.newRow();
        Map map = list.get(i);
        for (String key : map.keySet()) {
            dataRow.set(key, map.get(key));
        }
        dataTable.getRows().add(dataRow);
    }
    return dataTable;
}

你可能感兴趣的:(java)