1、标题注解
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface FieldChinese {
String name() default "";
}
2、 Excel导出
public static void export(HttpServletResponse response, Class clazz, List<?> list,
String excelName, String title) throws Exception {
if (!list.isEmpty()) {
if (!list.get(0).getClass().equals(clazz)) {
logger.error("数据类型与传入的集合数据类型不一致!数据类型:{}; 集合数据类型:{}", clazz, list.get(0).getClass());
throw new LogicException("数据类型与传入的数据类型不一致!");
} else {
ExcelWriter writer = ExcelUtil.getWriter();
Field[] fields = clazz.getDeclaredFields();
List<String> fieldNames = new ArrayList<>();
List<String> cnNames = new ArrayList<>();
for (Field field : fields) {
if (!field.isAccessible()) {
field.setAccessible(true);
}
String fieldName = field.getName();
if (!"sid".equals(fieldName) && !"serialVersionUID".equals(fieldName) && !"ordernum"
.equals(fieldName)) {
fieldNames.add(fieldName);
}
boolean annotationPresent = field.isAnnotationPresent(FieldChinese.class);
if (annotationPresent && !"sid".equals(fieldName)) {
FieldChinese annotation = field.getAnnotation(FieldChinese.class);
String name = annotation.name();
cnNames.add(name);
}
}
String[] fs = fieldNames.toArray(new String[0]);
String[] ns = cnNames.toArray(new String[0]);
for (int i = 0; i < ns.length; i++) {
writer.addHeaderAlias(fs[i], ns[i]);
}
Workbook workbook = writer.getWorkbook();
StyleSet styleSet = new StyleSet(workbook);
styleSet.setWrapText();
writer.setStyleSet(styleSet);
StyleSet style = writer.getStyleSet();
CellStyle headCellStyle = style.getHeadCellStyle();
Font font = writer.createFont();
font.setBold(true);
font.setFontHeightInPoints((short) 14);
headCellStyle.setFont(font);
writer.setStyleSet(style);
writer.merge(fs.length - 1, title, false);
writer.write(list, true);
ServletOutputStream out = response.getOutputStream();
try {
for (int i = 0; i < fieldNames.size(); i++) {
writer.setColumnWidth(i, 23);
}
response.setContentType("application/x-msdownload;charset=utf-8");
String ecodeFileName = URLEncoder.encode(excelName, "UTF-8") + LocalDate.now();
response.setHeader("Content-Disposition",
"attachment;filename=" + ecodeFileName + ";" + "filename*=utf-8''" + ecodeFileName
+ ".xls");
writer.flush(out, true);
writer.close();
IoUtil.close(out);
} catch (IOException e) {
logger.error(e.getMessage());
e.printStackTrace();
throw new FeignException(500, "程序内部发生错误,数据导出异常");
}
}
} else {
logger.error("数据集合为空");
throw new FeignException(500, "暂无数据,无法导出;");
}
}