1、pom中需要引入
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.0.7</version>
</dependency>
2、controller層
3、工具類
public class ExcelUtils {
/**
* 私有化構造方法
*/
private ExcelUtils() {
}
/**
*
* @param response HttpServletResponse
* @param fileName 導出文件名稱,不傳默認文件名爲"excel"
* @param headerAlias 表頭別名(源名稱-別名)
* @param data 表中數據 集合類型
*/
public static void excelExport(HttpServletResponse response, String fileName, Map<String, String> headerAlias, Iterable<?> data) {
ExcelWriter writer = null;
ServletOutputStream out = null;
try {
//文件名爲null或者""時,設置默認文件名
URLEncoder.encode(StrUtil.isEmpty(fileName) ? "excel" : fileName, "UTF-8");
response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xls");
// 通過工具類創建writer,創建xls格式
writer = ExcelUtil.getWriter();
if (MapUtil.isNotEmpty(headerAlias)) {
//給表頭設置別名
headerAlias.forEach(writer::addHeaderAlias);
}
// 一次性寫出內容,使用默認樣式,強制輸出標題
if (CollUtil.isNotEmpty(data)) {
writer.write(data, true);
}
//out爲OutputStream,需要寫出到的目標流
out = response.getOutputStream();
writer.flush(out);
} catch (IOException e) {
log.error("將數據寫入到excel表格中失敗", e);
} finally {
if (writer != null) {
writer.close();
}
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
log.error("將數據寫入到excel表格中失敗", e);
}
}
}
}