经常会遇到给用户提供数据下载的场景,将相关数据导出为Excel,因此对此进行了相关工具方法的封装:
pom:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
Controller层调用:
@GetMapping("download")
public void downloadAnnualBudget(@RequestParam("businessYear") Integer year,
@RequestParam(value = "version", required = false) Integer version,
HttpServletResponse httpResponse) {
// 获取待下载数据
List<AnnualBudgetDownLoadBo> dataset = annualBudgetService.getBudget(year, version);
String[] headers = {"资源类型", "单价", "折扣", "预算量", 计费量"};
download(annualBudgetDownLoadBos, headers, httpResponse);
}
工具类封装:
public class ExportExcelUtils<T> {
private static final Logger logger = LoggerFactory.getLogger(ExportExcelUtils.class);
/**
* 导出无头部标题行Excel, 时间格式默认:yyyy-MM-dd hh:mm:ss
* @param workbook
* @param title
* @param dataset
*/
public static <T> void exportExcel(XSSFWorkbook workbook, String title, Collection<T> dataset) {
exportExcel2007(workbook,title, null, dataset);
}
/**
* 导出带头部标题行Excel, 时间格式默认:yyyy-MM-dd hh:mm:ss
* @param workbook
* @param title
* @param headers
* @param dataset
*/
public static <T> void exportExcel(XSSFWorkbook workbook, String title, String[] headers, Collection<T> dataset) {
exportExcel2007(workbook,title, headers, dataset);
}
/**
* 通用E