记录一次关于java 导出word的代码
public class WordService {
public void exportWord(String title) throws IOException {
River river = new River();
XWPFTemplate template1 = XWPFTemplate.compile("~/Users/liwenna/Documents/" + "template.docx").render(river);
RowRenderData row0 = Rows.of("姓名", "性别", "学费信息", "", "", "年龄").center().create();
XWPFTemplate template = XWPFTemplate.compile("template.docx").render(
new HashMap<String, Object>(){{
put("title", "Hi, poi-tl Word模板引擎");
}});
template.writeToFile("output.docx");
}
public void exportFile() throws Exception {
String wordPath = "pwd";
String modelName = "template.docx";
String outputName = "test1.docx";
PictureRenderData picture = Pictures.ofUrl("url", PictureType.PNG).size(100, 100).create();
PictureRenderData netPicture = Pictures.ofUrl("url", PictureType.PNG).size(100, 100).create();
// 表格
List<RowRenderData> row = new ArrayList<>();
row.add(Rows.of("小明", "男", "2000", "5000", "1", "18").center().create());
row.add(Rows.of("小红", "女", "3000", "8000", "1", "18").center().create());
RowRenderData row0 = Rows.of("firstrow", "", "", "", "", "").center().create();
RowRenderData row1 = Rows.of("cow1", "cow2", "cow3", "cow4", "cow5", "cow6").center().create();
// 表格合并
MergeCellRule rule = MergeCellRule.builder().map(
MergeCellRule.Grid.of(0, 0), MergeCellRule.Grid.of(0, 5)).
build();
TableRenderData table = Tables.of(row0, row1, row.iterator().next()).mergeRule(rule).create();
// 数据封装
UserInfo userInfo = new UserInfo();
userInfo.setTitle("name");
userInfo.setGender("gender");
userInfo.setRemark("remark");
userInfo.setPicture(picture);
userInfo.setNetPicture1(netPicture);
userInfo.setTable(table);
// 传入模板模板地址+信息数据
XWPFTemplate template = XWPFTemplate.compile(wordPath + modelName).render(userInfo);
FileOutputStream out;
try {
// 将结果输出到目标位置
out = new FileOutputStream(wordPath + outputName);
template.write(out);
out.flush();
out.close();
template.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}