工作中遇到使用原生excel导出,如果要设置多表头或者特殊格式可以用到这个工具类方法。记录一下。
public AjaxResult export1(List<AqTraincompleterecordVO> list, String orgName){
String filename = "再教育培训详情统计"+ UUID.randomUUID() +".xlsx";
String resource = "static" + File.separator + "excel" + File.separator + "aq" + File.separator + "jyxqtj1.xlsx";
Resource classPathResource = new ClassPathResource(resource);
FileOutputStream out = null;
try {
InputStream in = classPathResource.getInputStream();
//读取excel模板
XSSFWorkbook wb = new XSSFWorkbook(in);
//读取了模板内所有sheet内容
XSSFSheet sheet = wb.getSheetAt(0);
//如果这行没有了,整个公式都不会有自动计算的效果的
sheet.setForceFormulaRecalculation(true);
// 在sheet里创建第一行,参数为行索引(excel的行),可以是0~65535之间的任何一个
XSSFCell row = sheet.getRow(1).createCell(0);
// 设置单元格内容
if("".equals(orgName)){
User user=getUser();
orgName=user.getOrgName();
}
row.setCellValue("单位:"+orgName);
//获取样式对象
XSSFCellStyle cellStyle = wb.createCellStyle();
//设置样式对象,这里仅设置了边框属性
cellStyle.setBorderBottom(BorderStyle.THIN); //下边框
cellStyle.setBorderLeft(BorderStyle.THIN);//左边框
cellStyle.setBorderTop(BorderStyle.THIN);//上边框
cellStyle.setBorderRight(BorderStyle.THIN);//右边框
cellStyle.setAlignment(HorizontalAlignment.CENTER);
//获取样式对象 百分比
XSSFCellStyle cellStyleBuiltin = wb.createCellStyle();
//设置样式对象,这里仅设置了边框属性
cellStyleBuiltin.setBorderBottom(BorderStyle.THIN); //下边框
cellStyleBuiltin.setBorderLeft(BorderStyle.THIN);//左边框
cellStyleBuiltin.setBorderTop(BorderStyle.THIN);//上边框
cellStyleBuiltin.setBorderRight(BorderStyle.THIN);//右边框
cellStyleBuiltin.setAlignment(HorizontalAlignment.CENTER);
XSSFDataFormat format = wb.createDataFormat();
cellStyleBuiltin.setDataFormat(format.getFormat("0.00")); // 两位小数
//在相应的单元格进行赋值
for (int i = 0; i < list.size(); i++) {
AqTraincompleterecordVO traincompleterecord = list.get(i);
XSSFRow creRow = sheet.createRow(i+3);
int cell=0;
XSSFCell cell1 = creRow.createCell(cell++);
cell1.setCellValue(i+1);
cell1.setCellStyle(cellStyle);
XSSFCell cell2 = creRow.createCell(cell++);
cell2 .setCellValue(traincompleterecord.getEmpName());
cell2.setCellStyle(cellStyle);
XSSFCell cell3 = creRow.createCell(cell++);
cell3.setCellValue(traincompleterecord.getEmpCode());
cell3.setCellStyle(cellStyle);
XSSFCell cell4 = creRow.createCell(cell++);
cell4.setCellValue(traincompleterecord.getOrgFullName());
cell4.setCellStyle(cellStyle);
}
String downloadPath = PaladinLiteProperties.getDownloadPath() + filename;
File desc = new File(downloadPath);
if (!desc.getParentFile().exists()) {
desc.getParentFile().mkdirs();
}
//修改模板内容导出新模板
out = new FileOutputStream(downloadPath);
wb.write(out);
} catch (Exception e) {
return AjaxResult.error("导出Excel失败");
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return AjaxResult.success(filename);
}