1:實(shí)體對(duì)象
@Data
@Accessors(chain = true)
public class UserExcelVO {
@Label("用戶號(hào)")
private String userNo;
@Label("期數(shù)")
private Integer suserNum;
@Label("金額")
private String amt;
}
@Target({ METHOD, FIELD })
@Retention(RUNTIME)
@Documented
public @interface Label {
String value() default "";
}
2:工具類
public class ExcelUtils {
public static <T> XSSFWorkbook createExcel(List<T> list, Class<T> clazz, String sheetName)
throws IllegalArgumentException, IllegalAccessException {
XSSFWorkbook workbook = new XSSFWorkbook();
addExcelSheet(list, clazz, workbook, sheetName);
return workbook;
}
public static <T> XSSFSheet addExcelSheet(List<T> list, Class<T> clazz, XSSFWorkbook workbook, String sheetName)
throws IllegalArgumentException, IllegalAccessException {
XSSFSheet sheet = workbook.createSheet(sheetName);
int sheetIndex = 0;
int sheetColumn = 0;
Field[] fields = clazz.getDeclaredFields();
int num = fields.length;
List<Field> usedFields = Lists.newArrayList();
// title
List<String> titles = Lists.newArrayList();
for (int i = 0; i < num; ++i) {
Field field = fields[i];
Annotation[] ans = field.getDeclaredAnnotations();
for (Annotation an : ans) {
if (an instanceof Label) {
Label label = (Label) an;
String value = label.value();
titles.add(value);
field.setAccessible(true);
usedFields.add(field);
}
}
}
Row row = sheet.createRow(sheetIndex++);
for (; sheetColumn < titles.size(); ++sheetColumn) {
row.createCell(sheetColumn).setCellValue(titles.get(sheetColumn));
}
// lines
for (T item : list) {
sheetColumn = 0;
row = sheet.createRow(sheetIndex++);
for (Field field : usedFields) {
Object fieldValue = field.get(item);
String value = fieldValue == null ? "" : fieldValue.toString();
row.createCell(sheetColumn++).setCellValue(value);
}
}
return sheet;
}
}
3:下載excel
@Override
@RequestMapping(value = "/download", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public void download(HttpServletResponse response) {
FileOutputStream fos = null;
try {
List<UserExcelVO> list = userService.finaAll();
XSSFWorkbook book = ExcelUtils.createExcel(
list, UserExcelVO.class,
"用戶交費(fèi)成功表");
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition",
"attachment; filename=" + "userList_" + cmd.getCompareBatchNo() + "_compareDetails.xlsx");
book.write(response.getOutputStream());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fos != null) {
IOUtils.closeQuietly(fos);
}
}
}