POI下载excel通用方法
最近遇到一个业务是需要下载excel,使用POI,这里记录一下实现过程
1、导包
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
2.公共方法的编写
package com.pingan.esbx.cassandra.util;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.util.CollectionUtils;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.Method;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;
public class ExcelDonload {
public static final String[] letters = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};
public static int rowNum = NumberUtils.INTEGER_ZERO;
public static DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public static <T> void donloadExcel(
String title,
List<T> resultList,
String fileName,
String[] tableTitles,
String[] titlesInfoKey,
String subtitle,
String[] desc,
HttpServletResponse response
) {
if (CollectionUtils.isEmpty(resultList)
|| tableTitles.length <= NumberUtils.INTEGER_ZERO) {
throw new RuntimeException("请求参数不正确!");
}
if (resultList.size() > 60000) {
throw new RuntimeException("到处数据超过6w,不能导出!");
}
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet();
setExcelTitle(workbook, sheet, title, tableTitles, subtitle, desc);
HSSFCellStyle dataStyle = workbook.createCellStyle();
dataStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
dataStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
for (int i = 0; i < resultList.size(); i++) {
T clazz = resultList.get(i);
insertDataToCell(sheet, clazz, titlesInfoKey, dataStyle);
}
File file = returnExcelDataStream(fileName, workbook);
buildResponseExcelFile(file, response);
}
private static void buildResponseExcelFile(File file, HttpServletResponse response) {
InputStream in = null;
OutputStream out = null;
try {
in = new FileInputStream(file.getPath());
response.reset();
response.setHeader("Content-disposition", "attachment;filename=" + new String(file.getName().getBytes(), "iso-8859-1"));
response.setContentType("application/octet-stream");
response.addHeader("Context-Length", "" + file.length());
response.setCharacterEncoding("utf-8");
out = response.getOutputStream();
int b;
while ((b = in.read()) != -1) {
out.write(b);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
file.delete();
}
private static File returnExcelDataStream(String fileName, HSSFWorkbook workbook) {
File file = null;
try {
String tempExcelPath = null;
if (StringUtils.isNotBlank(fileName)) {
tempExcelPath = File.separator + fileName + ".xls";
} else {
tempExcelPath = File.separator + "report.xls";
}
file = new File(tempExcelPath);
file.deleteOnExit();
file.createNewFile();
FileOutputStream fileOutputStream = FileUtils.openOutputStream(file);
workbook.write(fileOutputStream);
fileOutputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
return file;
}
private static <T> void insertDataToCell(HSSFSheet sheet, T clazz, String[] titlesInfoKey, HSSFCellStyle dataStyle) {
HSSFRow row = sheet.createRow(rowNum);
row.setHeight((short) (15 * 20));
for (int j = 0; j < titlesInfoKey.length; j++) {
HSSFCell cell = row.createCell(j);
cell.setCellStyle(dataStyle);
Object fieldValue = getValueByReflect(titlesInfoKey[j], clazz);
String cellResult = null;
if (fieldValue instanceof Date) {
cellResult = getStringTime((Date) fieldValue);
} else {
cellResult = Objects.isNull(fieldValue) ? "" : String.valueOf(fieldValue);
}
cell.setCellValue(cellResult);
}
rowNum += NumberUtils.INTEGER_ONE;
}
private static void setExcelTitle(HSSFWorkbook workbook,
HSSFSheet sheet,
String title,
String[] tableTitles,
String subtitle,
String[] desc) {
int cellMergedRegionNm = NumberUtils.INTEGER_ZERO;
int descLength = NumberUtils.INTEGER_ZERO;
rowNum = NumberUtils.INTEGER_ZERO;
if (desc != null) {
descLength = desc.length;
cellMergedRegionNm += descLength;
rowNum += descLength;
}
if (StringUtils.isNotBlank(subtitle)) {
cellMergedRegionNm += NumberUtils.INTEGER_ONE;
}
if (StringUtils.isNotBlank(title)) {
cellMergedRegionNm += NumberUtils.INTEGER_ONE;
}
int tableTitleLength = tableTitles.length;
String letter = getLetterByNum(tableTitleLength);
for (int i = 0; i < cellMergedRegionNm; i++) {
sheet.addMergedRegion(CellRangeAddress.valueOf("$A$" + (i + 1) + ":$" + letter + "$" + (i + 1)));
}
HSSFPalette palette = workbook.getCustomPalette();
palette.setColorAtIndex((short) 9, (byte) 240, (byte) 240, (byte) 240);
palette.setColorAtIndex((short) 10, (byte) 255, (byte) 153, (byte) 102);
palette.setColorAtIndex((short) 11, (byte) 100, (byte) 149, (byte) 137);
palette.setColorAtIndex((short) 12, (byte) 176, (byte) 196, (byte) 222);
HSSFFont workbookFont = workbook.createFont();
workbookFont.setFontName("仿宋");
workbookFont.setFontHeightInPoints((short) 14);
HSSFFont titleFont = workbook.createFont();
titleFont.setFontName("黑体");
titleFont.setFontHeightInPoints((short) 18);
titleFont.setColor(IndexedColors.WHITE.index);
HSSFCellStyle descStyleLong = workbook.createCellStyle();
descStyleLong.setFont(workbookFont);
descStyleLong.setFillForegroundColor((short) 9);
descStyleLong.setFillPattern(CellStyle.SOLID_FOREGROUND);
HSSFCellStyle descStyleShort = workbook.createCellStyle();
descStyleShort.setFont(workbookFont);
descStyleShort.setFillForegroundColor((short) 10);
descStyleShort.setFillPattern(CellStyle.SOLID_FOREGROUND);
HSSFCellStyle titleStyle = workbook.createCellStyle();
titleStyle.setFont(titleFont);
titleStyle.setFillForegroundColor((short) 11);
titleStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
titleStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
titleStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
HSSFRow row = null;
HSSFCell cell = null;
if (descLength > 0) {
for (int i = 0; i < descLength; i++) {
row = sheet.createRow(i);
row.setHeight((short) (23 * 20));
cell = row.createCell(0);
cell.setCellValue(desc[i]);
if (i >= 4) {
row.setHeight((short) (40 * 20));
cell.setCellStyle(descStyleShort);
} else {
cell.setCellStyle(descStyleLong);
}
}
}
if (StringUtils.isNoneBlank(title)) {
row = sheet.createRow(rowNum);
row.setHeight((short