文章目录
代码细节
使用的hutool的WordUtil,WordUtil对poi进行封装,但是这一块的官方封装的很少,很多细节都没有。代码中是常见的绘制段落,标题、表格等常用api
sql
Word07Writer writer = WordUtil.getWriter();
// 添加段落(标题)
DateTime dateTime = DateUtil.parseDate(month + "-01");
String format = DateUtil.format(dateTime, "yyyy年M月");
writer.addText(ParagraphAlignment.CENTER, new Font("方正小标宋简体", Font.BOLD, 15), StrUtil.format("{}{}抽蓄电站运行月报", format, stName));
//添加正文
writer.addText(ParagraphAlignment.LEFT, new Font("宋体", Font.BOLD, 10), "一、综合运行数据");
List<Entity> table = new ArrayList<>();
for (int i = 0; i < itemList.size(); i++) {
Entity entity = Entity.create();
entity.set("指标", itemList.get(i));
entity.set("单位", unit.get(i));
switch (i) {
case 0:
entity.set("数值", result.getStr("机端发电量"));
break;
case 1:
entity.set("数值", result.getStr("机端抽水电量"));
break;
case 2:
entity.set("数值", result.getStr("发电次数"));
break;
default:
entity.set("数值", result.getStr(itemList.get(i)));
}
entity.set("备注", beizhuList.get(i));
table.add(entity);
}
XWPFTable xwpfTable = TableUtil.createTable(writer.getDoc(), table);
// 遍历所有行
for (XWPFTableRow row : xwpfTable.getRows()) {
row.setHeight(500);
row.setCantSplitRow(true);
// 遍历行中的所有单元格
for (XWPFTableCell cell : row.getTableCells()) {
cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);//垂直居中
//设置宽度
cell.getCTTc().addNewTcPr().addNewTcW().setW(BigInteger.valueOf(100 * 25)); // 100磅转换为EMUs
CTTc cttc = cell.getCTTc();
CTP ctp = cttc.getPList().get(0);
CTPPr ctppr = ctp.getPPr();
if (ctppr == null) {
ctppr = ctp.addNewPPr();
}
CTJc ctjc = ctppr.getJc();
if (ctjc == null) {
ctjc = ctppr.addNewJc();
}
ctjc.setVal(STJc.CENTER); //水平居中
}
}
效果图
效果还是很不错的,相关打码了