Controller层
@GetMapping("/export")
@ApiOperation(value = "导出excel")
public void export(HttpServletResponse response, Product product) {
productDownExcelService.export(response, product);
}
service层
@Override
public void export(HttpServletResponse response, Product product) {
String fileName = "" + System.currentTimeMillis();
List<Product> products = productDao.selectPrice(product.getCat(), product.getMonthNum(), product.getTaskId().longValue());
EasyExcleUtils.download(response, data(products), Product.class, fileName);
}
util类
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
/**
* 转Excle文件工具类
*
*/
public class EasyExcleUtils {
public void download(HttpServletResponse response, List<?> excelInfoList, String name, Class<?> pojo) {
Workbook workbook = null;
ServletOutputStream outputStream = null;
try {
// 设置响应输出的头类型及下载文件的默认名称
String fileName = new String(name.getBytes("GB2312"), "ISO-8859-1");
fileName = URLEncoder.encode(fileName, "utf-8");
response.setContentType("application/octet-stream;charset=utf-8");
response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
//导出
workbook = ExcelExportUtil.exportExcel(new ExportParams(), pojo, excelInfoList);
outputStream = response.getOutputStream();
response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xls");//默认Excel名称
workbook.write(outputStream);
} catch (IOException e) {
logger.error("请求 exportExcel 异常:{}", e.getMessage(), e);
throw new RuntimeException("请求 exportExcel 异常:" + e.getMessage(), e);
} finally {
if (workbook != null) {
try {
workbook.close();
} catch (IOException e) {
throw new RuntimeException("workbook 关闭异常:" + e.getMessage(), e);
}
}
if (outputStream != null) {
try {
outputStream.flush();
outputStream.close();
} catch (IOException e) {
throw new RuntimeException("outputStream 关闭异常:" + e.getMessage(), e);
}
}
}
}
}