easypoi---Excel file export

A .pom file imports jar

        <dependency>
			<groupId>cn.afterturn</groupId>
			<artifactId>easypoi-base</artifactId>
			<version>3.2.0</version>
		</dependency>
		<dependency>
			<groupId>cn.afterturn</groupId>
			<artifactId>easypoi-web</artifactId>
			<version>3.2.0</version>
		</dependency>
		<dependency>
			<groupId>cn.afterturn</groupId>
			<artifactId>easypoi-annotation</artifactId>
			<version>3.2.0</version>
		</dependency>

2. Create tool class

public class ExcelUtils {
	/**
	 * excel 导出
	 *
	 * @param list         要导出的数据
	 * @param pojoClass    pojo类型
	 * @param fileName     文件名称
	 * @param exportParams 导出表格参数
	 * @param response
	 */
	public static void exportExcel(List<?> list, Class<?> pojoClass, String fileName, ExportParams exportParams,
			HttpServletResponse response) throws IOException {
		Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list);
		downLoadExcel(fileName, response, workbook);
	}

	public static void exportExcel(ExportParams exportParams, List<ExcelExportEntity> colList, List<?> list,HttpServletResponse response)
			throws IOException {
		Workbook workbook = ExcelExportUtil.exportExcel(exportParams, colList, list);
		downLoadExcel(exportParams.getSheetName(), response, workbook);
	}

	/**
	 * 下载文件
	 *
	 * @param fileName 文件名称
	 * @param response
	 * @param workbook excel数据
	 */
	private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook)
			throws IOException {
		try {
			response.setHeader("Access-Control-Allow-Origin","*");
			response.setCharacterEncoding("UTF-8");
			response.setHeader("content-Type", "application/vnd.ms-excel");
			response.setHeader("Content-Disposition",
					"attachment;filename=" + URLEncoder.encode(fileName + ".xls", "UTF-8"));
			OutputStream output=response.getOutputStream();
			workbook.write(output);
			output.flush();
			workbook.close();
			output.close();
		} catch (Exception e) {
			throw new IOException(e.getMessage());
		}
	}
}

3. Create entity class

public class ElePfvEnergyDTO implements Serializable{
	
	private static final long serialVersionUID = 1L;

	@Excel(name = "工序名称", width = 20)
    private String name;

    @Excel(name = "电量", groupName = "尖", width = 20, orderNum = "0")
    private Double top;

    @Excel(name = "电费", groupName = "尖", width = 20, orderNum = "1")
    private Double topCost;

    @Excel(name = "电量", groupName = "高", width = 20, orderNum = "0")
    private Double high;
    
    @Excel(name = "电费", groupName = "高", width = 20, orderNum = "1")
    private Double highCost;
    
    @Excel(name = "电量", groupName = "平", width = 20, orderNum = "0")
    private Double flat;
    
    @Excel(name = "电费", groupName = "平", width = 20, orderNum = "1")
    private Double flatCost;
    
    @Excel(name = "电量", groupName = "谷", width = 20, orderNum = "0")
    private Double valley;
    
    @Excel(name = "电费", groupName = "谷", width = 20, orderNum = "1")
    private Double valleyCost;
    
    @Excel(name = "电量", groupName = "总计", width = 20, orderNum = "0")
    private Double allEle;
    
    @Excel(name = "电费", groupName = "总计", width = 20, orderNum = "1")
    private Double allCost;
}

4. In the ExportParams class, find the ExcelExportStylerDefaultImpl class, copy the content and generate a new class (used to set the excel header background, font, position, etc.)

 

/**
 * 样式的默认实现
 * @author JueYue
 *  2015年1月9日 下午5:36:08
 */
public class ExcelExportStylerImpl extends AbstractExcelExportStyler
                                          implements IExcelExportStyler {

    public ExcelExportStylerImpl(Workbook workbook) {
        super.createStyles(workbook);
    }

    @Override
    public CellStyle getTitleStyle(short color) {
        CellStyle titleStyle = workbook.createCellStyle();
        Font font = this.workbook.createFont();
        font.setBold(true);
        titleStyle.setFont(font);
        titleStyle.setAlignment(HorizontalAlignment.CENTER);
        titleStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        titleStyle.setWrapText(true);
        titleStyle.setBorderRight(BorderStyle.THIN);
        titleStyle.setBorderTop(BorderStyle.THIN);
        titleStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        titleStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        return titleStyle;
    }

    @Override
    public CellStyle stringSeptailStyle(Workbook workbook, boolean isWarp) {
        CellStyle style = workbook.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        style.setDataFormat(STRING_FORMAT);
        if (isWarp) {
            style.setWrapText(true);
        }
        return style;
    }

    @Override
    public CellStyle getHeaderStyle(short color) {
        CellStyle titleStyle = workbook.createCellStyle();
        Font font = workbook.createFont();
        font.setFontHeightInPoints((short) 12);
        titleStyle.setFont(font);
        return titleStyle;
    }

    @Override
    public CellStyle stringNoneStyle(Workbook workbook, boolean isWarp) {
        CellStyle style = workbook.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        style.setDataFormat(STRING_FORMAT);
        if (isWarp) {
            style.setWrapText(true);
        }
        return style;
    }

}

5. Controller layer call

@RequestMapping(value = "/exportPFYXls")
	public void exportXls(HttpServletResponse response) {

		List<ElePfvEnergyDTO> list = service.getAreaCodeList();
    	String fileName = "明细表";
        String sheetName = "明细表";
        ExportParams exportParams = new ExportParams();
        exportParams.setSheetName(sheetName);
        exportParams.setStyle(ExcelExportStylerImpl.class);
        exportParams.setCreateHeadRows(true);
        exportParams.setHeaderHeight(500D);
        try {
        	ExcelUtils.exportExcel(list,ElePfvEnergyDTO.class,fileName,exportParams,response);
        } catch (Exception e) {
            e.printStackTrace();
        }
	}

6. Display:

 Seven: vertical cell merge

There are two attributes in the excel annotation NeedMerge: whether to merge; MergeVertical: vertical merge

@Excel(name = "电量", groupName = "尖", width = 20, orderNum = "0" ,mergeVertical = true, needMerge = true)

8. Dynamic header:

1. Manual splicing header:

public List<ExcelExportEntity> getHeadList(EnParamsVo vo){
    	List<String> dateList = new ArrayList<String>();
		for (int i = 0; i < vo.getSelCount(); i++) {
			String thisDay = DateUtil.getSpecifiedDayBefore(vo.getSelDate(), i);
			dateList.add(thisDay);
		}
		Collections.reverse(dateList);
    	List<ExcelExportEntity> colList = new ArrayList<ExcelExportEntity>();
        //第一列
        ExcelExportEntity colEntity1 = new ExcelExportEntity("名称", "name");
        colEntity1.setNeedMerge(true);
        colEntity1.setMergeVertical(true);
        colList.add(colEntity1);
        //第二列
        ExcelExportEntity colEntity2 = new ExcelExportEntity("类别", "type");
        colEntity2.setNeedMerge(true);
        colList.add(colEntity2);
        for(String localDate:dateList){
            ExcelExportEntity dateColGroup = new ExcelExportEntity(localDate, localDate);
            List<ExcelExportEntity> dateColList = new ArrayList<ExcelExportEntity>();
            ExcelExportEntity tempExcelExportEntity = new ExcelExportEntity(DateUtil.getWeekOfDate(localDate), "dayOfWeek"+localDate);
            dateColList.add(tempExcelExportEntity);
            dateColGroup.setList(dateColList);
            colList.add(dateColGroup);
        }
        return colList;
    }

2. Manual splicing value:

public List<Map<String, Object>> getExcelList(Map<String, Object> map, String name) {
		List<String> dateList = (List<String>) map.get("xList");  
		List<String> outputList = (List<String>) map.get("outputList");
		List<String> electricList = (List<String>) map.get("electricList");
    	List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
    	List<String> typeList = Arrays.asList("test1","test2","test3","test4","test5","test6");
        for(int i=0;i < typeList.size();i++){
            Map<String, Object> valMap = new HashMap<>();
            valMap.put("name", name);
            valMap.put("type",typeList.get(i));
            	for(int j=0;j < dateList.size();j++){
                    List<Map<String, Object>> dayOfWeekList = new ArrayList<Map<String, Object>>();
                    Map<String, Object> dayOfWeekMap = new HashMap<String, Object>();
                    if (i == 1) {
                    	dayOfWeekMap.put("dayOfWeek"+ dateList.get(j), outputList.get(j));
					}else if(i == 2) {
						dayOfWeekMap.put("dayOfWeek"+ dateList.get(j), electricList.get(j));
					}
					else {
						dayOfWeekMap.put("dayOfWeek"+ dateList.get(j), 0);
					}	
                    dayOfWeekList.add(dayOfWeekMap);
                    valMap.put(dateList.get(j), dayOfWeekList);
                }
 
            list.add(valMap);
        }
        return list;
    }

3. Export:

public void exportMCUOfDay(EnParamsVo vo, HttpServletResponse response){
        List<ExcelExportEntity> colList = getHeadList(vo);
        List<String> idList = eStruService.getNodeListByDeptIdAndLevel(vo.getSelCode(), "3");
        List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
        if (CollectionUtils.isEmpty(idList)) {
			return;
		}
        idList.forEach(r->{
        	vo.setSelCode(r);
        	String name = eStruService.getOne(new QueryWrapper<EnergyStructure>().eq("id", r)).getName();
    		QueryWrapper<EnergyStructure> queryWrapper = new QueryWrapper<EnergyStructure>();
    		if (CollectionUtils.isNotEmpty(idList)) {
    			queryWrapper.eq("parent_id", r);
    		} else {
    			queryWrapper.eq("id", "");
    		}
    		queryWrapper.isNotNull("code");
    		List<String> centerNameList = eStruService.list(queryWrapper).stream().map(x ->x.getCode())
    				.collect(Collectors.toList());
    		if (CollectionUtils.isEmpty(centerNameList)) {
    			centerNameList = Arrays.asList("1");
    		}
    		Map<String, Object> map =  queryMCUOfDay(vo, centerNameList);
    		list.addAll(getExcelList(map,name));
        });
        String sheetName = "用电明细";
        ExportParams exportParams = new ExportParams();
        exportParams.setSheetName(sheetName);
        exportParams.setStyle(ExcelExportStylerImpl.class);
        exportParams.setCreateHeadRows(true);
        exportParams.setHeaderHeight(500D);
        try {
        	ExcelUtils.exportExcel(exportParams, colList,list, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
        
    }

exhibit:

 

Guess you like

Origin blog.csdn.net/yiye2017zhangmu/article/details/121769448