poi导出简单Excel模板(通用)
通用的表头模板下载,需要填入表头名称;
main:
String[] title = new String[]{"主合同号", "结清日期", "贷款起期", "贷款止期", "贷款金额"};
createDownExcel(Arrays.asList(title), response, "结清清单模板.xls", "application/vnd.ms-excel");
业务逻辑
/**
* 生成下载模板
*
* @param titles 生成得表头
* @param fileName 生成的文件名
* @param contentType contentType
*/
public void createDownExcel(List<String> titles, HttpServletResponse resp, String fileName, String contentType) throws Exception {
resp.addHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));
resp.setContentType(contentType);
resp.setCharacterEncoding("UTF-8");
ExportExcelUtils.createDownTemplate((Row row) -> {
HSSFPatriarch p = (HSSFPatriarch)row.getSheet().createDrawingPatriarch();
for (int i = 0; i < titles.size(); i++) {
Cell cell = row.createCell(i);
cell.setCellType(CellType.STRING);
String strVal = titles.get(i);
if( strVal.contains("@") ) {
HSSFComment comment = p.createComment(new HSSFClientAnchor(i+1, 0, i+1,0, (short) 3, 3, (short) 5, 6));
// 输入批注信息
String []arrs = strVal.split("@");
comment.setString(new HSSFRichTextString(arrs[1]));
// 将批注添加到单元格对象中
cell.setCellComment(comment);
cell.setCellValue(arrs[0]);
} else {
//写入数据
cell.setCellValue(strVal);
}
}
}, resp.getOutputStream());
}
ExportExcelUtils.java
//生成下载模板
public static void createDownTemplate(POICallBack callBack, OutputStream os) {
HSSFWorkbook book = null;
try {
//创建table工作薄
book = new HSSFWorkbook();
HSSFSheet sheet = book.createSheet("Sheet1");
//创建标题行
HSSFRow rowTitle = sheet.createRow(0);
callBack.doInPOI(rowTitle);
book.write(os);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != book) {
try {
book.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
POICallBack.java
public interface POICallBack {
void doInPOI(Row row) throws Exception;
}