1 使用的pom文件
<dependency>
<groupId>com.deepoove</groupId>
<artifactId>poi-tl</artifactId>
<version>1.10.2</version>
</dependency>
2 创建模板文件
注意:模板文件最好是docx格式的。
3 关键代码分析
单元格居中,创建行的时候使用如下的方式
RowRenderData row0 = Rows.of("序号", "年份","事件").center().create();
表格列宽自适应
Tables.TableBuilder tableBuilder = Tables.ofAutoWidth();
如果不设置列宽自适应,生成的表格可能是这个样子的
设置之后是这样的,格式会好看些
4 关于poi-tl
此组件的使用方式在这里不在赘述。详见官方文档,介绍的很详细。
5 完整代码
package io.rong.example.word;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.data.*;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class WordTemplatePage {
private static String wordPath="C:\\Users\\Administrator\\Desktop\\ticket\\template.docx";
private static String wordPath1="C:\\Users\\Administrator\\Desktop\\ticket\\result.docx";
private static String photoPath="C:\\Users\\Administrator\\Desktop\\ticket\\kobe.jpg";
public WordTemplatePage(){
}
public static void main(String[] args) throws IOException {
Map<String, Object> data = new HashMap<>();
data.put("name","科比");
//单元格居中
RowRenderData row0 = Rows.of("序号", "年份","事件").center().create();
RowRenderData row1 = Rows.of("1", "2000","NBA总冠军").center().create();
RowRenderData row2 = Rows.of("2", "2001","NBA总冠军").center().create();
RowRenderData row3 = Rows.of("3", "2002","NBA总冠军").center().create();
RowRenderData row4 = Rows.of("4", "2009","NBA总冠军").center().create();
RowRenderData row5 = Rows.of("5", "2010","NBA总冠军").center().create();
RowRenderData row6 = Rows.of("6", "2016","谢幕战60分力压勇士73胜").center().create();
//列宽自适应
Tables.TableBuilder tableBuilder = Tables.ofAutoWidth();
//Tables.TableBuilder tableBuilder = Tables.ofAutoWidth().center();表格整体居中
TableRenderData tableRenderData = tableBuilder.create();
tableRenderData.addRow(row0);
tableRenderData.addRow(row1);
tableRenderData.addRow(row2);
tableRenderData.addRow(row3);
tableRenderData.addRow(row4);
tableRenderData.addRow(row5);
tableRenderData.addRow(row6);
data.put("list", tableRenderData);
data.put("photo", Pictures.ofStream(new FileInputStream(photoPath), PictureType.JPEG)
.size(100, 120).create());
XWPFTemplate template = XWPFTemplate.compile(wordPath).render(data);
FileOutputStream out;
out = new FileOutputStream(wordPath1);
template.write(out);
out.flush();
out.close();
template.close();
}
}
6 结果
版权声明:本文为u010667011原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。