/**
* 按模板导出excel
* @param response
* @param templatePath 要导出的模板路径
* @param sourceList 数据集合
* @param targetClass 目标class类
* @param insertRow 插入的起始行数
* @throws Exception
*/
public static void exportByTempBySelfCon(
HttpServletResponse response,
String templatePath,
Collection<?> sourceList,
Class<?> targetClass,
int insertRow,
List<CellContent> cellConList) throws Exception {
Workbook workbook =null;
OutputStream os = null;
ServletOutputStream out = null;
try {
ClassPathResource resource = new ClassPathResource(templatePath);
InputStream inputStream = resource.getInputStream();
boolean isExcel2003 = templatePath.toLowerCase().endsWith("xls")?true:false;
if(isExcel2003){
workbook = new HSSFWorkbook(inputStream);
}else{
workbook = new XSSFWorkbook(inputStream);
}
Sheet sheet = workbook.getSheetAt(0);//sheet页开始行
JSONArray json= JSONArray.parseArray(JSON.toJSONString(sourceList));//todo
cusFormCont(cellConList,sheet);//插入自定义内容
//得到class的属性列表
int dataStartRow =insertRow;//数据开始插入的行数
Class clazz = targetClass;
Field[] fs=clazz.getDeclaredFields();
for (int i = 0; i < json.size() ; i++) {
int cellNum = 0;
JSONObject obj = json.getJSONObject(i);
if (obj.size()>0) {
Row dataRows = sheet.createRow(dataStartRow +i);
for(Field f:fs){//f为单个属性
f.setAccessible(true); //设置私有属性的访问权限
dataRows.createCell(cellNum).setCellValue(obj.get(f.getName())==null?"":obj.get(f.getName())+"") ;
cellNum++;
}
}
}
//response.setCharacterEncoding("UTF-8");
//todo 升级spingboot 报错后,注掉
response.setHeader("content-Type", "application/vnd.ms-excel");
response.setHeader("Content-Disposition",
"attachment;filename=" + URLEncoder.encode("excelexport"+DateUtils.formatNoSign(new Date()), "UTF-8") + ".xlsx");
out = response.getOutputStream();
workbook.write(out);
out.flush();
} catch (IOException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} finally {
if(out!=null){
out.close();
}
if(workbook!=null){
workbook.close();
}
}
}
Java 按模板导出excel
最新推荐文章于 2024-02-26 16:19:18 发布