gradle 导入 org.apache.poi:poi-ooxml:3.14
HSSFWorkbook用来处理较少的数据量,
SXSSFWorkbook用来处理超大数据量的导出,20w数据没什么问题。
注意导出文件后缀 (.xlsx)
public class ExcelUtils {
public static void exportExcel(HttpServletResponse response,List<String> sheetList, List<List<String>> rowList, String fileName) {
OutputStream output = null;
try {
SXSSFWorkbook workbook = new SXSSFWorkbook();
SXSSFSheet sheet = workbook.createSheet();
SXSSFRow firstRow = sheet.createRow(0);
for(int i = 0; i < sheetList.size(); i++){
firstRow.createCell(i).setCellValue(sheetList.get(i));
}
int rowNum = 1;
for(int i = 0; i < rowList.size(); i++){
SXSSFRow row = sheet.createRow(rowNum);
List<String> detailRowList = rowList.get(i);
for (int j = 0; j < detailRowList.size(); j++) {
row.createCell(j).setCellValue(detailRowList.get(j));
}
rowNum++;
}
output = response.getOutputStream();
response.reset();
response.setContentType("application/x-download");
response.setCharacterEncoding("utf-8");
response.setHeader("Content-Disposition", "attachment;filename="
+ new String(fileName.getBytes("gbk"), "iso8859-1")+".xlsx");
workbook.write(output);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (output != null) {
output.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}