easypoi导出验证及校验码认证,模板唯一认证

动态导出文件,客户把文件信息补充完整,导入文件时,需要校验文件的真实性及文件的唯一性,确保导入的文件是单据的!

// 动态导出文件
@ApiOperation(value = "填报登记模板下载")
    @PostMapping(value = "/xxx/templateDownLoad")
    public void download(@RequestBody String jsonString, @RequestHeader("x-user-token") String token, HttpServletResponse response) {
        // 生成初始化,list内放需要导出的数据
        List<TemplateVo> findList = new ArrayList<>();
        Model model = JSON.parseObject(jsonString, Model.class);
        String msgid = model.getMsgid();
        if (StringUtils.isEmpty(msgid)){
            logger.info("未获取到唯一标识");
            throw new BusizException("唯一标识不能为空");
        }
        // 取得sql或者业务的内容
        findList = xxxService.getAll(model);
        try {
            //设置单元格位置
            CellRangeAddress cellAddresses = new CellRangeAddress(0, 0, 0, 0);
            //1.创建excel文档对象
            XSSFWorkbook wb = new XSSFWorkbook();
            //样式
            Map<String, XSSFCellStyle> cellStyle = createCellStyle(wb);
            //2.创建sheet对象
            XSSFSheet sheet = wb.createSheet("模板");
            //创建提示标题信息
            XSSFRow row0 = sheet.createRow(0);
            createTitle(row0, cellAddresses, sheet, cellStyle,msgid);
            //3.创建表头,创建第一行
            XSSFRow row1 = sheet.createRow(1);
            createHeaders(row1, cellAddresses, sheet, cellStyle);
            //填充数据
            createDataCellFdplPlan(findList1, sheet, cellStyle);
            //设置列宽
            setColumnLength(sheet);
            // 设置日期信息
            Calendar now = Calendar.getInstance();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String dateNowStr = sdf.format(now.getTime());
            // 开启流
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            wb.write(bos);
            byte[] bytes = bos.toByteArray();
            bos.close();
            response.setHeader("Content-Disposition", "attachment; filename=\"iJEP_" + dateNowStr + ".xlsx\"");
            response.addHeader("Content-Length", "" + bytes.length);
            response.setContentType("application/octet-stream; charset=UTF-8");
            IOUtils.write(bytes, response.getOutputStream());
            logger.info("登记模板--附件下载完成!");
        } catch (Exception e) {
            logger.info("登记模板--附件下载失败!" + e);
        }

    }
 // 样式设计   
 private Map<String, XSSFCellStyle> createCellStyle(XSSFWorkbook wb){
        Map<String, XSSFCellStyle> styles = new HashMap();
        XSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        style.setBorderRight(BorderStyle.THIN);
        style.setRightBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
        style.setBorderLeft(BorderStyle.THIN);
        style.setLeftBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
        style.setBorderTop(BorderStyle.THIN);
        style.setTopBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
        style.setBorderBottom(BorderStyle.THIN);
        style.setBottomBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
        Font dataFont = wb.createFont();
        dataFont.setFontName("Arial");
        dataFont.setFontHeightInPoints((short)12);
        style.setFont(dataFont);
        styles.put("data", style);


        style = wb.createCellStyle();
        style.cloneStyleFrom((XSSFCellStyle)styles.get("data"));
        style.setAlignment(HorizontalAlignment.LEFT);
        Font dataFont2 = wb.createFont();
        dataFont2.setFontName("Arial");
        dataFont2.setFontHeightInPoints((short)12);
        dataFont2.setColor(Font.COLOR_RED);
        style.setFont(dataFont2);
        style.setIndention((short)2);
        styles.put("data1", style);


        style = wb.createCellStyle();
        style.cloneStyleFrom((XSSFCellStyle)styles.get("data"));
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        style.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.getIndex());
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        Font headerFont = wb.createFont();
        headerFont.setFontName("Arial");
        headerFont.setFontHeightInPoints((short)10);
        headerFont.setBold(true);
        headerFont.setColor(IndexedColors.WHITE.getIndex());
        style.setFont(headerFont);
        styles.put("header", style);

        style = wb.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        Font totalFont = wb.createFont();
        totalFont.setFontName("Arial");
        totalFont.setColor(Font.COLOR_RED);
        totalFont.setFontHeightInPoints((short)10);
        style.setFont(totalFont);
        styles.put("total", style);

        style = wb.createCellStyle();
        style.cloneStyleFrom((XSSFCellStyle)styles.get("data"));
        style.setAlignment(HorizontalAlignment.LEFT);
        styles.put("data2", style);

        style = wb.createCellStyle();
        style.cloneStyleFrom((XSSFCellStyle)styles.get("data"));
        style.setAlignment(HorizontalAlignment.CENTER);
        styles.put("data3", style);

        style = wb.createCellStyle();
        style.cloneStyleFrom((XSSFCellStyle)styles.get("data"));
        style.setAlignment(HorizontalAlignment.RIGHT);
        styles.put("data4", style);
        return styles;
    }
    private void createTitle(XSSFRow row0, CellRangeAddress cellAddresses, XSSFSheet sheet, Map<String, XSSFCellStyle> style, String msgid) {
        XSSFCell cell0 = row0.createCell(0);
        cell0.setCellValue("注意:模版编号为:"+msgid+",仅填写子节点项目即红色字体部分");
        XSSFCellStyle style1 = style.get("total");
        style1.setWrapText(true);
        cell0.setCellStyle(style1); //为单元格设置样式
        cellAddresses.setFirstRow(0); // 第一行的内容进行合并
        cellAddresses.setLastRow(0);
        cellAddresses.setFirstColumn(0); // 合并 从第一列开始
        cellAddresses.setLastColumn(2); // 合并 最后一列的表示
        sheet.addMergedRegion(cellAddresses);
    }
    // 创建标题
 private void createHeaders(XSSFRow row1, CellRangeAddress cellAddresses, XSSFSheet sheet, Map<String, XSSFCellStyle> style) {
        // 第一行
        XSSFCell cell0 = row1.createCell(0);
        cell0.setCellValue("项目编号");
        cell0.setCellStyle(style.get("header"));//为单元格设置样式

        XSSFCell cell1 = row1.createCell(1);
        cell1.setCellValue("项目");
        cell1.setCellStyle(style.get("header"));//为单元格设置样式

        XSSFCell cell2 = row1.createCell(2);
        cell2.setCellValue("金额(元)");
        cell2.setCellStyle(style.get("header"));//为单元格设置样式
    }
    private void createDataCellFdplPlan(List<TemplateVo> findList, XSSFSheet sheet, Map<String, XSSFCellStyle> style) {
      if (findList!=null&&findList.size()>0){
          for (int i = 0; i < findList.size(); i++) {
              XSSFRow rowi = sheet.createRow(i + 2);
              TemplateVo templateVo = findList.get(i);
              for (int j = 0; j <1 ; j++) {
                  XSSFCell cell0 = rowi.createCell(j+0);
                  cell0.setCellValue(templateVo .getPlanItemCod());
                  cell0.setCellStyle(style.get("data2"));//为单元格设置样式

                  XSSFCell cell1 = rowi.createCell(j+1);
                  if ("0".equals(templateVo .getIsSuperCode())){
                      cell1.setCellValue("*"+templateVo .getPlanItemNam());
                      XSSFCellStyle style1 = style.get("data1");
                      style1.setWrapText(true);
                      cell1.setCellStyle(style1);//为单元格设置样式
                  }else{
                      cell1.setCellValue(templateVo .getPlanItemNam());
                      XSSFCellStyle style2 = style.get("data2");
                      style2.setWrapText(true);
                      cell1.setCellStyle(style2);//为单元格设置样式
                  }

                  XSSFCell cell2 = rowi.createCell(j+2);
                  cell2.setCellValue("");
                  cell2.setCellStyle(style.get("data4"));//为单元格设置样式
              }


          }
      }
    }
    // 设置列宽
     private void setColumnLength(XSSFSheet sheet) {
        sheet.autoSizeColumn(0,true);
        sheet.autoSizeColumn(1,true);
        int width = sheet.getColumnWidth(1)+1600;
        sheet.setColumnWidth(1,width);
        sheet.setColumnWidth(2,5000);

    }

动态导出文件,特别表示的最好在第一行或者最后一行
导出文件
导入文件设置:

// 导入文件,从第几行开始验证,怎么读取第一行数据
 @ApiOperation(value = "上传内容")
  
    @PostMapping(value = "/import/upload")
    public ResponseBean upload(@RequestParam(value = "file") MultipartFile file, TempleVo templeVo , @ApiIgnore @RequestHeader(WebHeaderCode.X_USER_TOKEN) String token){
        FdpPlanRegisterReturnVo fdpPlanRegisterReturn = new FdpPlanRegisterReturnVo(); // 错误信息及成功信息的返回信息
        // 前端传来的唯一标识
        String msgid = templeVo .getMsgid();
        if ("".equals(msgid) || null == msgid) {
            logger.info("未获取到计划唯一标识");
            return ResponseBean.fail("未获取到计划唯一标识!");
        }
        InputStream is = null;
        try {
            is = file.getInputStream(); // 前端传来的文件
            if (is == null) {
                logger.info("计划填报登记导入模板");
                fdpPlanRegisterReturn.setCode("401");
                fdpPlanRegisterReturn.setMessage("计划填报登记导入模板");
                return ResponseBean.success(fdpPlanRegisterReturn);
            }
            //模版校验 is 不要进行重新赋值,不然流会变空
            String msg = checkTemplet(msgid, file.getInputStream());
            if (StringUtils.isNotEmpty(msg)){
                return ResponseBean.fail(msg);
            }
            UserInfoCache cacheInfo = userInfoService.getCacheInfo(token); // 从token获取用户信息
            // 解析数据
            ImportParams params = new ImportParams();
            params.setTitleRows(1); // 标题从有几行
            params.setHeadRows(1); // 从第几行开始读取
            params.setStartRows(1); // 开始的行数
          
            logger.info("解析数据开始");
            // ExportExcel 你要映射的实体类
            List<ExportExcel> plans = ExcelImportUtil.importExcel(is, ExportExcel.class, params);
            logger.info("解析数据结束");
            if (plans != null && plans.size() == 0) {
                logger.info("计划填报登记导入模板无数据");
                fdpPlanRegisterReturn.setCode("401");
                fdpPlanRegisterReturn.setMessage("计划填报登记导入模板无数据");
                return ResponseBean.success(fdpPlanRegisterReturn);
            }
            //数据校验 等
			String msg  = xxService.checkData(plans );
            return ResponseBean.success(fdpPlanRegisterReturn);
        } catch (NoSuchElementException e) {
            fdpPlanRegisterReturn.setCode("402");
            fdpPlanRegisterReturn.setMessage("excel文件不能为空");
            return ResponseBean.success(fdpPlanRegisterReturn);
        }catch (Exception e) {
            if(e instanceof ExcelImportException){
                fdpPlanRegisterReturn.setCode("402");
                fdpPlanRegisterReturn.setMessage("请使用系统指定模板上传文件");
                return ResponseBean.success(fdpPlanRegisterReturn);
            }
            if(e instanceof IllegalArgumentException){
                fdpPlanRegisterReturn.setCode("402");
                fdpPlanRegisterReturn.setMessage("请使用系统指定模板上传文件");
                return ResponseBean.success(fdpPlanRegisterReturn);
            }
            logger.error("解析文件异常:" + e);
            return ResponseBean.fail("解析文件异常");
        }finally {
            try {
                if(is != null){
                    is.close();
                }
            } catch (IOException e) {
                logger.error("", e);
            }
        }
    }
    // 根据唯一标识校验模板是否是这个单据的
private String checkTemplet(String msgid, InputStream is) {
        Workbook book = null;
        String title = null;
        String msg = "";
        try {
            book = xxxxService.importExcel(is);
            Sheet sheet = book.getSheetAt(0);
            title = sheet.getRow(0).getCell(0).getStringCellValue();
            if ("".equals(title) || null == title) {
                msg = "标题不能为空";
            } else {
                int first = title.lastIndexOf(":")+1;
                int last = title.lastIndexOf(",");
                String templeteId = title.substring(first, last);
                if (null==templeteId||""==templeteId){
                    msg = "模版编号不能为空";
                }else{
                    if (!msgid.equals(templeteId)){
                        msg = "模版编号不一致,请检查导入模版是否为同一模版";
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return msg;
    }

实体类设置

package com.pactera.ts.service.fdpl.vo;

import cn.afterturn.easypoi.excel.annotation.Excel;
import io.swagger.annotations.ApiModelProperty;

import java.math.BigDecimal;

public class FdplPlanExportExcel {
    // isImportField excel表格里必须有这个字段,报错内容为:请使用系统指定模板上传文件
    @ApiModelProperty("资金计划项目编号")
    @Excel(name = "资金计划项目编号",orderNum = "0",isImportField = "true")
    private String planItemCod;

    @ApiModelProperty("资金计划项目")
    @Excel(name = "资金计划项目",orderNum = "1",isImportField = "true")
    private String planItemNam;

    @ApiModelProperty("计划金额(元)")
    @Excel(name = "计划金额(元)",orderNum = "2",isImportField = "true",numFormat="#,##0.00")
    private BigDecimal planAmt;

    public String getPlanItemCod() {
        return planItemCod;
    }

    public void setPlanItemCod(String planItemCod) {
        this.planItemCod = planItemCod;
    }

    public String getPlanItemNam() {
        return planItemNam;
    }

    public void setPlanItemNam(String planItemNam) {
        this.planItemNam = planItemNam;
    }

    public BigDecimal getPlanAmt() {
        return planAmt;
    }

    public void setPlanAmt(BigDecimal planAmt) {
        this.planAmt = planAmt;
    }

    @Override
    public String toString() {
        return "FdplPlanExportVo{" +
                "planItemCod='" + planItemCod + '\'' +
                ", planItemNam='" + planItemNam + '\'' +
                ", planAmt=" + planAmt +
                '}';
    }
}

  • 11
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在使用Easypoi导出Excel模板时,如果需要在模板中添加签名图片,可以按照以下步骤进行配置: 1. 首先,确保你已经引入了Easypoi的相关依赖包,并在项目中进行了配置。 2. 创建一个Excel模板文件,可以使用Excel软件进行创建。在需要添加签名图片的位置,可以插入一个图片占位符,例如在单元格中插入一个文本“[img]”。 3. 在Java代码中,使用Easypoi提供的API来读取模板文件,并进行相应的配置。具体步骤如下: a. 创建一个Excel导出的实体类,用于存储导出数据的字段。 b. 使用`ExcelExportUtil`类的`exportExcel`方法来读取模板文件,并获取`Workbook`对象。 c. 使用`Workbook`对象的相关方法,如`getSheet`、`getRow`、`getCell`等,定位到需要添加签名图片的位置。 d. 使用Easypoi提供的`ImageEntity`类,创建一个图片实体对象,并设置图片的路径、宽度、高度等属性。 e. 使用`Workbook`对象的`addImage`方法,将图片实体对象添加到指定位置。 f. 最后,使用`ExcelExportUtil`类的`exportExcel`方法将修改后的Workbook对象导出为Excel文件。 4. 在导出Excel时,将实际的签名图片路径设置到图片实体对象中,以替换占位符。 下面是一个示例代码,演示了如何使用Easypoi导出带签名图片的Excel模板: ```java // 创建导出实体类 public class ExportEntity { // 其他字段... private String signatureImage; // 签名图片路径 // getter和setter方法... } // 导出Excel的方法 public void exportExcelWithSignature() { // 读取模板文件 Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), ExportEntity.class, new ArrayList<>()); // 获取Sheet对象 Sheet sheet = workbook.getSheetAt(0); // 获取需要添加签名图片的位置 Row row = sheet.getRow(1); Cell cell = row.getCell(1); // 创建图片实体对象 ImageEntity imageEntity = new ImageEntity(); imageEntity.setUrl("path/to/signature.png"); // 设置签名图片路径 imageEntity.setWidth(100); // 设置图片宽度 imageEntity.setHeight(50); // 设置图片高度 // 添加图片到指定位置 sheet.addImage(imageEntity, cell); // 导出Excel文件 ExcelExportUtil.exportExcel(workbook, "output.xlsx"); } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值