自定义数据,excel导出

获取要导出的数据

 public JsonResult exportExcel(@Valid BVehicleRunning query, HttpServletResponse response) throws Exception {

        if("true".equals(query.getForceCommit())){
            List<BVehicleRunning> bVehicleRunnings = this.listCar(query);
            String fileName = "车次数据信息_"  + DatesUtils.now(DatesUtils.DF_TIMESTAMP) +".xls";
            fileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.toString());
            response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName + "\"; filename*=utf-8''" + fileName );
            this.exportHistoryVehicle(response.getOutputStream(), bVehicleRunnings);
            return JsonResult.confirm("0000","success","");
        }else {
            Integer integer = this.beforeExportExcel(query);
            if(integer==null){
                return JsonResult.confirm("0002","你没有权限导出数据,请先申请场站权限","");
            }else if(integer>15000){
                return JsonResult.confirm("0001","导出数据量过大,导出时间较长,是否继续导出","");
            }else {
                List<BVehicleRunning> bVehicleRunnings = this.listCar(query);
                String fileName = "车次数据信息_"  + DatesUtils.now(DatesUtils.DF_TIMESTAMP) +".xls";
                fileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.toString());
                response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
                response.setHeader("Content-Disposition", "attachment;filename=" + fileName + "\"; filename*=utf-8''" + fileName );
                this.exportHistoryVehicle(response.getOutputStream(), bVehicleRunnings);
                return JsonResult.confirm("0000","success","");
            }
        }





    }

导出的工具类

public static boolean exportHistoryVehicle(OutputStream outputStream, List<BVehicleRunning> dataList) {
        Workbook wb = new HSSFWorkbook();
        Sheet sheet = wb.createSheet("sheet");

        Set<String> vehiHeads = HistoryVehicleUtil.historyFeildDescs();
        creatHead(wb, sheet, vehiHeads);

        int rowIndex = 1, cellIndex = 0;
        Cell cell = null;
        Row row = null;
        try {
            if (CollectionUtils.isNotEmpty(dataList)) {
                for (BVehicleRunning data : dataList) {
                    row = sheet.createRow(rowIndex++);
                    cellIndex = 0;
                    for (String fieldDesc : vehiHeads) {
                        cell = row.createCell(cellIndex++);
                        cell.setCellType(CellType.STRING);
                        cell.setCellValue((String) HistoryVehicleUtil.getVehiFieldValue(data, fieldDesc));
                    }
                }
            }
            wb.write(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                wb.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return true;
    }
package com.samples.web.util;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.samples.common.enumerate.ElecFence;
import com.samples.common.enumerate.IsWarnEnum;
import com.samples.common.enumerate.LastGateFlowEnum;
import com.samples.common.enumerate.WipeStatus;
import com.samples.web.dict.WarnType;
import com.samples.web.entity.BVehicleRunning;
import com.samples.web.entity.PParamInfo;
import com.samples.web.service.PParamInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Cell;
import org.springframework.beans.factory.annotation.Autowired;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.*;


@Slf4j
public class HistoryVehicleUtil {


    private static Map<String, String> historyFeild = new LinkedHashMap<String, String>();

    static {
        historyFeild.put("车牌号", "veName");
        historyFeild.put("二维码", "barCode");
        historyFeild.put("卡口放行单号", "guid");
        historyFeild.put("放行状态", "lcpPassStatusName");
        historyFeild.put("所在场站", "areaName");
        historyFeild.put("所在功能区", "fenceName");
        historyFeild.put("核销状态", "wipeStatus");
        historyFeild.put("是否预警", "isWarn");
        historyFeild.put("预警类型", "warnType");
        historyFeild.put("最近卡口流向", "lastGateFlow");
        historyFeild.put("主卡进入时间", "enterTime");
        historyFeild.put("主卡出场时间", "exitTime");
        historyFeild.put("创建时间", "createTime");
    }

    public static Set<String> historyFeildDescs() {


        return historyFeild.keySet();
    }


    private static Date parseDate(Cell cell) {
        Date date = null;
        try {
            date = DatesUtils.parse(cell.getStringCellValue(), DatesUtils.DF_2_SECOND);
        } catch (Exception e) {
        }
        return (null == date) ? cell.getDateCellValue() : date;
    }

    public static Object getVehiFieldValue(BVehicleRunning vehicle, String fieldDesc) {
        String fieldName = historyFeild.get(fieldDesc);

        Object value = null;
        Field field = null;
        try {
            field = vehicle.getClass().getDeclaredField(fieldName);
            field.setAccessible(true);
            value = field.get(vehicle);
        } catch (NoSuchFieldException e) {
            log.error("获取HistoryVehicleDTO字段: " + fieldName + ", 字段不存在");
        } catch (SecurityException e) {
            log.error("获取HistoryVehicleDTO字段: " + fieldName + ", e: " + e.getMessage());
        } catch (IllegalAccessException e) {
            log.error("获取HistoryVehicleDTO字段: " + fieldName + ", 非法访问");
        }

        if (null == value) return "";
        if (value instanceof Date) return DatesUtils.format((Date) value, DatesUtils.DF_2_SECOND);
        String filedValue = value.toString();
        if ("wipeStatus".equals(fieldName)) return WipeStatus.desc(filedValue);
        if("isWarn".equals(fieldName)) return IsWarnEnum.desc(filedValue);
        if("warnType".equals(fieldName)){
            if(StringUtils.isNotEmpty(filedValue)){
                String[] split = filedValue.split("/");
                ArrayList<Object> arrList = new ArrayList<>();
                List<WarnType> list = WarnType.list;
                for(String s:split){
                    for (WarnType ss:list){
                        if(s.equals(ss.getCode())){
                            arrList.add(ss.getName());
                            break;
                        }
                    }
                }
                //判断集合是不是空
                if (CollectionUtils.isNotEmpty(arrList)) {
                    //集合转字符串
                    String join = org.apache.commons.lang3.StringUtils.join(arrList, "/");
                    return join;
                }
            }
        }
        if ("lastGateFlow".equals(fieldName)){
            if (StringUtils.isNotEmpty(filedValue)){
                List<LastGateFlowEnum> list = LastGateFlowEnum.list;
                for (LastGateFlowEnum s :list){
                    if(filedValue.equals(s.getCode())){
                        return s.getName();
                    }
                }
            }
        }
        return filedValue;
    }

    private static byte[] path2Image(String path) {
        File photoFile = new File(path);
        if (photoFile.exists()) {
            try {
                BufferedImage bufferedImage = ImageIO.read(photoFile);
                ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
                ImageIO.write(bufferedImage, "jpg", byteArrayOut);
                return byteArrayOut.toByteArray();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;

    }
}```



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值