不废话直接上代码
/**
*
* Excel文件生成类
* 工具包POI
*/
public class ExcelUtils {
/**
* 创建workBook
* @return
*/
public static XSSFWorkbook createExcelWorkBook(){
return new XSSFWorkbook();
}
/**
* 从获取枚举类中获取单元格样式
* @param workbook
* @param cellStyleEnum 单元格样式枚举类
* @return
*/
public static CellStyle getCellStyle(XSSFWorkbook workbook, CellStyleEnum cellStyleEnum){
CellStyle cellStyle = cellStyleEnum.getCellStyle(workbook);
return cellStyle;
}
/**
* 创建sheet
* @param xssfWorkbook
* @param sheetName sheet名
* @return
*/
public static XSSFSheet createAndGetExcelSheet(XSSFWorkbook xssfWorkbook,String sheetName){
XSSFSheet sheet = xssfWorkbook.createSheet(sheetName);
return sheet;
}
/**
* 将数据生成到sheet
* @param sheet
* @param cellStyle 单元格样式
* @param dataList 数据列表
* @param <T>
* @throws BusinessException
*/
public static <T> void writeExcelCell(XSSFSheet sheet,CellStyle cellStyle, List<T> dataList) throws BusinessException{
if(ObjectUtils.isEmpty(dataList)){
return;
}
T t1 = dataList.get(0);
Field[] declaredFields = t1.getClass().getDeclaredFields();
//列名和字段的映射关系
LinkedHashMap<String,Field> linkedHashMap = new LinkedHashMap<>(declaredFields.length);
for(Field field:declaredFields){
ExcelField declaredAnnotation = field.getDeclaredAnnotation(ExcelField.class);
//包含ExcelField注解的才在Excel文件中展示
if(declaredAnnotation!=null){
field.setAccessible(true);
linkedHashMap.put(declaredAnnotation.columnName(),field);
}
}
String[] columnNames = linkedHashMap.keySet().toArray(new String[]{});
if(linkedHashMap.isEmpty()){
throw new BusinessException("Sheet无可输出的列,请检查对象是否包含@ExcelField");
}
//先打印列名
for(int i=0;i<columnNames.length;i++){
writeExcelCell(sheet,cellStyle,columnNames[i],0,i);
}
//余下值从第1行开始输出
int beginRow =1;
for(int i=0;i<dataList.size();i++){
for(int j=0;j<columnNames.length;j++){
try {
writeExcelCell(sheet,cellStyle,linkedHashMap.get(columnNames[j]).get(dataList.get(i)),i+beginRow,j);
} catch (IllegalAccessException e) {
throw new BusinessException(String.format("导出Excel文件出现数据异常,原因[%s],异常值为[%s]",e.getMessage(),GsonUtil.getGson().toJson(dataList.get(i))));
}
}
}
//让sheet的列宽自适应
for(int j=0;j<columnNames.length;j++) {
sheet.autoSizeColumn(j);
}
}
/**
* 创建单元格和录入值
* @param sheet
* @param data
* @param row
* @param column
*/
public static void writeExcelCell(XSSFSheet sheet,CellStyle cellStyle, Object data, int row, int column){
XSSFRow xssfRow = executeFunctionIfNull(sheet, sheet.getRow(row), a -> a.createRow(row));
XSSFCell cell = executeFunctionIfNull(xssfRow, xssfRow.getCell(column), a -> a.createCell(column));
cell.setCellStyle(cellStyle);
setCellTypeAndValue(data,cell);
}
/**
* 创建单元格类型和设置值
* @param data
* @param cell
*/
public static void setCellTypeAndValue(Object data,XSSFCell cell){
if(data == null){
return ;
}
if(data instanceof Number){
cell.setCellType(CellType.NUMERIC);
cell.setCellValue(Double.parseDouble(data.toString()));
}else if(data instanceof Boolean){
cell.setCellType(CellType.BOOLEAN);
cell.setCellValue(Boolean.valueOf(data.toString()));
}else{
cell.setCellType(CellType.STRING);
cell.setCellValue(data.toString());
}
}
/**
* 如果obj为空,则使用t和function构造相同类型的返回,否则返回obj
* @param t
* @param obj
* @param function
* @param <T>
* @param <R>
* @return
*/
public static <T,R> R executeFunctionIfNull(T t, R obj, Function<T,R> function){
if(obj==null){
return function.apply(t);
}
return obj;
}
/**
* 直接将workBook输出给用户
* @param request
* @param response
* @param workbook
* @param fileName
* @throws BusinessException
*/
public static void downloadExcelFile(HttpServletRequest request, HttpServletResponse response, XSSFWorkbook workbook,String fileName) throws BusinessException{
if(workbook==null){
throw new BusinessException("workBook为空,Excel文件生成失败");
}
if(fileName==null){
fileName = "excel";
}
//文件名可以不指定文件格式,统一生成xlsx格式。
fileName = fileName.replaceAll("\\..*","")+".xlsx";
String userAgent = Optional.ofNullable(request.getHeader("user-agent")).orElse("").toLowerCase();
OutputStream toClient = null;
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
try{
if (userAgent.contains("msie") || userAgent.contains("like gecko")) {
// win10 ie edge 浏览器 和其他系统的ie
fileName = URLEncoder.encode(fileName, "UTF-8");
}else {
// fe
fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
}
workbook.write(byteArrayOutputStream);
byte[] bytes = byteArrayOutputStream.toByteArray();
// 清空response
response.reset();
// 设置response的Header
response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
response.addHeader("Content-Length",String.valueOf(bytes.length));
//说明返回对象类型是文件
response.setContentType("application/octet-stream");
toClient = new BufferedOutputStream(response.getOutputStream());
workbook.write(toClient);
toClient.write(bytes);
toClient.flush();
}catch (Exception e){
throw new BusinessException(String.format("下载文件出现异常,文件名:[%s],异常信息[%s]",fileName,e.getMessage()));
}finally {
if(toClient!=null){
try {
toClient.close();
} catch (IOException e) {
throw new BusinessException(String.format("下载文件后关闭IO输出流出现异常,原因[%s]",e.getMessage()));
}
}
try {
byteArrayOutputStream.close();
} catch (IOException e) {
throw new BusinessException(String.format("下载文件后关闭用于辅助展示文件大小的IO输出流出现异常,原因[%s]",e.getMessage()));
}
}
}
}
上述的BusinessException是自定义的运行时异常类,如下:
public class BusinessException extends RuntimeException{
public BusinessException(String message) {
super(message);
}
public BusinessException(Throwable cause){
super(cause);
}
}
自定义的注解ExcelField(当时设计是这么考虑的,要打印的字段总要有列名,因此作用在字段上,因此考虑使用自定义注解,方便理解):
import java.lang.annotation.*;
/**
* 自定义注解,配合ExcelUtils工具类使用,无该注解的字段不输出到Excel文件中
*/
@Target(ElementType.FIELD)
@Documented
@Retention(RetentionPolicy.RUNTIME)
public @interface ExcelField {
/**
* 表头名
* @return
*/
public String columnName();
}
自定义的样式枚举类如下:
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
/**
*/
/**
* Excel单元格的样式枚举类
* @author dd-zhanjx
*/
public enum CellStyleEnum {
/**
* DEFAULT 默认样式,上下左右边框为细边,12字号的宋体
*/
DEFAULT{
@Override
public CellStyle getCellStyle(XSSFWorkbook workbook) {
CellStyle cellStyle = workbook.createCellStyle();
//设置上下左右边框样式
cellStyle.setBorderBottom(BorderStyle.THIN);
cellStyle.setBorderLeft(BorderStyle.THIN);
cellStyle.setBorderRight(BorderStyle.THIN);
cellStyle.setBorderTop(BorderStyle.THIN);
//设置字体大小和样式
Font font = workbook.createFont();
font.setFontName("宋体");
font.setFontHeightInPoints(new Short("12"));
cellStyle.setFont(font);
return cellStyle;
}
};
public abstract CellStyle getCellStyle(XSSFWorkbook workbook);
}
public class SubscribeUserBO {
@ExcelField(columnName = "用户名")
private String userName;
public String getUserName() {
return userName;
}
public void setClientName(String userName) {
this.userName = userName;
}
}
使用ExcelUtils的Demo
public void demo(HttpServletRequest request, HttpServletResponse response,List<XXXclass> data){
XSSFWorkbook excelWorkBook = ExcelUtils.createExcelWorkBook();
XSSFSheet xssfSheet = ExcelUtils.createAndGetExcelSheet(excelWorkBook, fundCode);
//获取默认单元格样式
CellStyle cellStyle = ExcelUtils.getCellStyle(excelWorkBook, CellStyleEnum.DEFAULT);
ExcelUtils.writeExcelCell(xssfSheet,cellStyle,data);
ExcelUtils.downloadExcelFile(request,response,excelWorkBook,"excel");
}
使用到的poi依赖(项目是使用gradle搭建的,需要pom格式的可以去maven仓库查询)
compile group: 'org.apache.poi', name: 'poi', version: '4.0.1'
compile group: 'org.apache.poi', name: 'poi-excelant', version: '4.0.1'
compile group: 'org.apache.poi', name: 'poi-scratchpad', version: '4.0.1'