說明
在此工具類中使用了hutool
工具包,具體依賴介紹參考官方https://www.hutool.cn/docs/#/poi/概述
以及 lombok
,在實體屬性中需加入@ApiModelProperty
注解,代碼中也有說明,有不明白的或者更好的方法歡迎留言。
配套前端代碼地址:前端接收下載后端文件流
/**
* @author: yang
* @Date: Create in 2020/7/16
* @Explain: 封裝hutool工具類實現的導出excel功能
*/
public class ExportExcelUtil {
static final Log logger = LogFactory.get(ExportExcelUtil.class);
public static void
export(HttpServletResponse response, Class clazz, List <? > list) throws Exception {
if(!list.isEmpty()) {
if(!list.get(0).getClass().equals(clazz)) {
logger.error("數據類型與傳入的集合數據類型不一致!數據類型:{}; 集合數據類型:{}", clazz, list.get(0).getClass());
throw new Exception("數據類型與傳入的集合數據類型不一致!");
} else {
ExcelWriter writer = ExcelUtil.getWriter();
// 獲取當前類字段
Field[] fields = clazz.getDeclaredFields();
// 字段名稱集合
List < String > fieldNames = new ArrayList < > ();
// 字段中文名稱集合(獲取實體中@ApiModelProperty注解value的值)
List < String > cnNames = new ArrayList < > ();
for(Field field: fields) {
if(!field.isAccessible()) {
// 關閉反射訪問安全檢查,為了提高速度
field.setAccessible(true);
}
String fieldName = field.getName();
// 排除ID和序號
if(!"sid".equals(fieldName) && !"serialVersionUID".equals(fieldName) && !"ordernum".equals(fieldName)) {
fieldNames.add(fieldName);
}
// 判斷是否有@ApiModelProperty注解
boolean annotationPresent = field.isAnnotationPresent(ApiModelProperty.class);
if(annotationPresent && !"sid".equals(fieldName)) {
ApiModelProperty annotation = field.getAnnotation(ApiModelProperty.class);
String name = annotation.value();
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);
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("excel", "UTF-8");
response.setHeader("Content-Disposition", "attachment;filename=" + ecodeFileName + ".xls");
writer.flush(out, true);
writer.close();
IoUtil.close(out);
} catch(IOException e) {
logger.error(e.getMessage());
e.printStackTrace();
}
}
} else {
logger.error("數據集合為空");
throw new Exception("數據集合為空");
}
}
}