SpringBoot中EasyExcel的集成和简单使用,excel导出功能的实现

添加依赖

        
        
            com.alibaba
            easyexcel
            2.2.6
        

controller层、service层、dao层不再赘述

核心代码,一般写在controller层

import com.alibaba.excel.EasyExcel;
import com.example.handler.CustomCellWriteHandler;
import com.example.service.DeptService;
import com.example.vo.DetpExcelVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
@RestController
@RequestMapping("/dept")
public class DeptController {
    @Autowired
    private DeptService deptService;

    @GetMapping("/export")
    public void export(HttpServletResponse response) {
        try {
            //设置传输的数据类型和编码方式
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("UTF-8");
            //设置下载的文件名和编码方式
            String fileName = URLEncoder.encode("文件名", "UTF-8");
            //设置响应头Content-disposition:下载的文件完整名
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            //获取ProductExcelVO类型的List
            List list = this.deptService.excelVOList();
            //导出,第一个是参数输出流,第二个是excel模板类的class对象
            EasyExcel.write(response.getOutputStream(), DetpExcelVo.class)
                    .registerWriteHandler(new CustomCellWriteHandler())//用于设置excel表格的格式,代码在下面
                    .sheet("子表格名")//设置子表格
                    .doWrite(list);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

模板类(创建vo包存放),用于和excel表格中的每一行数据对应

import com.alibaba.excel.annotation.ExcelProperty;
import lombok.Data;

@Data
public class DetpExcelVo {
    @ExcelProperty("部门编号")
    private Integer deptno;

    @ExcelProperty("部门名")
    private String dname;

    @ExcelProperty("部门地点")
    private String loc;

}
@ExcelProperty("部门编号")
private Integer deptno;

部门编号表示生成excel表格后,deptno对应的名字

SpringBoot中EasyExcel的集成和简单使用,excel导出功能的实现_第1张图片

用于设计excel表格格式的类(创建一个handler包存放)

import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.util.CollectionUtils;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.style.column.AbstractColumnWidthStyleStrategy;
import org.apache.poi.ss.usermodel.Cell;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CustomCellWriteHandler extends AbstractColumnWidthStyleStrategy {
    private Map> CACHE = new HashMap<>();
    @Override
    protected void setColumnWidth(WriteSheetHolder writeSheetHolder, List cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
        boolean needSetWidth = isHead || !CollectionUtils.isEmpty(cellDataList);
        if (needSetWidth) {
            Map maxColumnWidthMap = CACHE.get(writeSheetHolder.getSheetNo());
            if (maxColumnWidthMap == null) {
                maxColumnWidthMap = new HashMap<>();
                CACHE.put(writeSheetHolder.getSheetNo(), maxColumnWidthMap);
            }
            Integer columnWidth = this.dataLength(cellDataList, cell, isHead);
            if (columnWidth >= 0) {
                if (columnWidth > 255) {
                    columnWidth = 255;
                }

                Integer maxColumnWidth = maxColumnWidthMap.get(cell.getColumnIndex());
                if (maxColumnWidth == null || columnWidth > maxColumnWidth) {
                    maxColumnWidthMap.put(cell.getColumnIndex(), columnWidth);
                    writeSheetHolder.getSheet().setColumnWidth(cell.getColumnIndex(), columnWidth * 256);
                }

            }
        }
    }
    private Integer dataLength(List cellDataList, Cell cell, Boolean isHead) {
        if (isHead) {
            return cell.getStringCellValue().getBytes().length;
        } else {
            CellData cellData = cellDataList.get(0);
            CellDataTypeEnum type = cellData.getType();
            if (type == null) {
                return -1;
            } else {
                switch (type) {
                    case STRING:
                        return cellData.getStringValue().getBytes().length;
                    case BOOLEAN:
                        return cellData.getBooleanValue().toString().getBytes().length;
                    case NUMBER:
                        return cellData.getNumberValue().toString().getBytes().length;
                    default:
                        return -1;
                }
            }
        }
    }
}

你可能感兴趣的:(spring,boot,java,spring)