SpringBoot工程,根据给定的word模板,生成word文件

推荐poi-tl(基于Apache POI的word模版引擎),中文文档地址http://deepoove.com/poi-tl/,文档介绍,清新明了!

项目里只使用了文本和表格

1.文本

数据源--使用@name注解

public class ObjectionHandle {
	private int id;
	private int recordId;//日志ID
	@Name("originator")
	private String originator;//发起人姓名
	@Name("knowDate")
	private String knowDate;//知晓日期
    ...
}

word模版截图如下:

SpringBoot工程,根据给定的word模板,生成word文件_第1张图片

2.表格(在一个已有的表格中,动态处理某些单元格数据)

模版截图:

生成模版到本地:

public void manageWordTemplate(String id) {
		FileOutputStream out = null;
		XWPFTemplate template = null;
		try {
			ObjectionHandle obj = this.manageComplaint(id);//分装好的文本数据源
			String path = '生成word的地址';
			List productlst = xxx;//表格的列表数据
			Configure config = Configure.newBuilder().customPolicy("detail_table", new DetailTablePolicy(productlst)).build();//模板标签{{detail_table}}设置成此策略
			template = XWPFTemplate.compile('模版的地址',config).render(obj);//渲染
			out = new FileOutputStream(baseURL);
			template.write(out);
			out.flush();
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			..各种关闭
		}
	}
//策略类
public class DetailTablePolicy extends DynamicTableRenderPolicy {
	// 货品填充数据所在行数
	int goodsStartRow = 2;
	
	private List productlst;
    //构造函数
	public DetailTablePolicy(List productlst) {
		super();
		this.productlst = productlst;
	}

	@Override
	public void render(XWPFTable table, Object data) {
		List goods = new ArrayList();
		for(ComplaintProduct p:productlst){
			RowRenderData good = RowRenderData.build(p.getCertificationNo(), p.getProductName(), p.getProductCode(), p.getLots(), "", p.getExpDate(), p.getSalesDate(),String.valueOf(p.getQty()));
			goods.add(good);
		}
		// 货品明细
		if (null != goods) {
			table.removeRow(goodsStartRow);
			for (int i = 0; i < goods.size(); i++) {
				XWPFTableRow insertNewTableRow = table.insertNewTableRow(goodsStartRow);
				for (int j = 0; j < 8; j++)
					insertNewTableRow.createCell();
				// 渲染单行货品明细数据
				MiniTableRenderPolicy.renderRow(table, goodsStartRow, goods.get(i));
			}
		}
	}
}

(SpringBoot中构建带有含参构造函数的Bean,报错Parameter 0 of constructor in XXX required a bean ...,解决参见:解决方法)

你可能感兴趣的:(SpringBoot工程,根据给定的word模板,生成word文件)