EasyPoi导出,设置不同列的字体颜色(修改easypoi 3.1.0版本源码)

news2024/11/16 0:44:15

声明:代码以esaypoi 3.1.0版本为基础,基本上新的代码都是直接copy源码的,只是稍微修改了源码;仍然需要导入该依赖是

<dependency>
    <groupId>cn.afterturn</groupId>
    <artifactId>easypoi-base</artifactId>
    <version>3.1.0</version>
</dependency>

和其他依赖

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.16</version>
</dependency>

需求人员要求对导出的excel重点列设置不同颜色,由于项目使用的是easypoi工具包,经过了一天的看源码,修改源码的痛苦时间.....最终找到源码的关键点进行修改。

例如要求将姓名,分数所在列用颜色字体进行展示

修改源码后导出内容:

 

需要这些类(文章末尾附源码):

其中类名后缀为 New 的类,大部分是直接复制源码的,重点在于修改

BaseExportServiceNew 类 和 ExcelExportStylerNew 类

顺便定义一个学生类用于导出

(注解@ColorFontFiled是我自定义的注解):

@Data
@Builder
@ExcelTarget(value = "apmOrderExportDTO")
public class StudentInfoDTO {
  @Excel(name = "学号", width = 30)
  private String orderNo;

  @ColorFontFiled(name = "姓名")
  @Excel(name = "姓名", width = 30)
  private String name;

  @Excel(name = "地址", width = 30)
  private String address;

  @ColorFontFiled(name = "分数")
  @Excel(name = "分数", width = 30)
  private Integer score;
}

自定义注解用于标注哪些列需要颜色突出

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public @interface ColorFontFiled {
  String name();
}

继承IExcelExportStylerNew类,编写样式类 ExcelExportStylerNew,这个类用于设置不同单元格的字体颜色 ,


public class ExcelExportStylerNew implements IExcelExportStylerNew {

  private static final short FONT_SIZE_TEN = 10;
  private static final short FONT_SIZE_ELEVEN = 11;
  private static final short FONT_SIZE_TWELVE = 12;
  private static final short STRING_FORMAT = (short) BuiltinFormats.getBuiltinFormat("TEXT");
  private CellStyle headerStyle;
  private CellStyle titleStyle;
  private CellStyle styles;

  public ExcelExportStylerNew(Workbook workbook) {
    this.init(workbook);
  }

  private void init(Workbook workbook) {
    this.headerStyle = this.initHeaderStyle(workbook);
    this.titleStyle = this.initTitleStyle(workbook);
    this.styles = this.initStyles(workbook);
  }



  @Override
  public CellStyle getHeaderStyle(short color) {
    return this.headerStyle;
  }

  @Override
  public CellStyle getTitleStyle(short color) {
    return this.titleStyle;
  }

  @Override
  public CellStyle getStyles(boolean parity, ExcelExportEntity entity) {
    return this.styles;
  }

  @Override
  public CellStyle getStyles(Cell cell, int dataRow, ExcelExportEntity entity, Object obj, Object data) {
    return this.getStyles(true, entity);
  }

  @Override
  public CellStyle getTemplateStyles(boolean isSingle, ExcelForEachParams excelForEachParams) {
    return null;
  }

  private CellStyle initHeaderStyle(Workbook workbook) {
    CellStyle style = this.getBaseCellStyle(workbook);
    style.setFont(this.getFont(workbook, (short)12, true));
    return style;
  }

  private CellStyle initTitleStyle(Workbook workbook) {
    CellStyle style = this.getBaseCellStyle(workbook);
    style.setFont(this.getFont(workbook, (short)11, false));
    style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
    style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
    return style;
  }

  private CellStyle initStyles(Workbook workbook) {
    CellStyle style = this.getBaseCellStyle(workbook);
    style.setFont(this.getFont(workbook, (short)10, false));
    style.setDataFormat(STRING_FORMAT);
    return style;
  }

  @Override
  public CellStyle getStylesColorFont(Workbook workbook, boolean flag) {
    CellStyle style = this.getBaseCellStyle(workbook);
    // 自定义的字体
    style.setFont(this.getFontByFlag(workbook, (short)10, false, flag));
    style.setDataFormat(STRING_FORMAT);
    return style;
  }

  private CellStyle getBaseCellStyle(Workbook workbook) {
    CellStyle style = workbook.createCellStyle();
    style.setBorderTop(BorderStyle.THIN);
    style.setBorderBottom(BorderStyle.THIN);
    style.setBorderLeft(BorderStyle.THIN);
    style.setBorderRight(BorderStyle.THIN);
    style.setAlignment(HorizontalAlignment.CENTER);
    style.setVerticalAlignment(VerticalAlignment.CENTER);
    style.setWrapText(false);
    return style;
  }

  private Font getFont(Workbook workbook, short size, boolean isBold) {
    Font font = workbook.createFont();
    font.setFontName("宋体");
    font.setBold(isBold);
    font.setFontHeightInPoints(size);
    return font;
  }
  
  private Font getFontByFlag(Workbook workbook, short size, boolean isBold, boolean flag) {
    Font font = workbook.createFont();
    font.setFontName("宋体");
    font.setBold(isBold);
    font.setFontHeightInPoints(size);
    if (flag) {
      // 根据flag设置列字体颜色 这里为蓝色
      font.setColor(IndexedColors.BLUE.getIndex());
    }
    return font;
  }
}

1. main方法用于测试导出是否正常:

public class TestExcelExport {
  public static void main(String[] args) {

    StudentInfoDTO infoDTO = StudentInfoDTO.builder()
        .orderNo("B1")
        .name("小明")
        .address("浙江")
        .score(95)
        .build();
    StudentInfoDTO infoDTO2 = StudentInfoDTO.builder()
        .orderNo("B2")
        .name("小红")
        .address("浙江")
        .score(96)
        .build();
    StudentInfoDTO infoDTO3 = StudentInfoDTO.builder()
        .orderNo("B3")
        .name("小蓝")
        .address("杭州")
        .score(90)
        .build();
    List<StudentInfoDTO> list = new ArrayList<>();
    list.add(infoDTO);
    list.add(infoDTO2);
    list.add(infoDTO3);
    exportExcel(StudentInfoDTO.class, list,500, true) ;

  }

  public static String exportExcel(Class<?> pojoClass, Collection<?> dataSet, int maxNum, boolean createHeaderFlag) {
    String saveFolder = "D:\\testConvert" + File.separator + "excel";
    String savePath = saveFolder + File.separator + System.currentTimeMillis() + ".xls";
    // 测试保存地址
    try {
      File createFolder = new File(saveFolder);
      if (!createFolder.exists()) {
        createFolder.mkdirs();
      }

      // 设置表头
      ExportParams exportParams = new ExportParams();
      exportParams.setMaxNum(maxNum == 0 ? 10000 : maxNum);
      // ExcelExportStylerNew 是我修改 ExcelExportStyler 类新建的,若不修改无法更改颜色字体
      exportParams.setStyle(ExcelExportStylerNew.class);
      exportParams.setCreateHeadRows(createHeaderFlag);
      long start = (new Date()).getTime();
      
      // 进入源码
      Workbook workbook = ExcelExportUtilNew.exportExcel(exportParams, pojoClass, dataSet);

      long cost = (new Date()).getTime() - start;
      System.out.println("excel导出耗时 = " + cost/1000 + "毫秒");
      FileOutputStream fos = new FileOutputStream(savePath);
      workbook.write(fos);
      fos.close();
    } catch (FileNotFoundException var12) {
      var12.printStackTrace();
    } catch (IOException var13) {
      var13.printStackTrace();
    }
    return savePath;
  }
}

2. 从上面的 ExcelExportUtilNew.exportExcel()方法进入下方类:

关于 ExcelExportUtilNew类,就是直接copy源码的,只是删掉多余代码

public class ExcelExportUtilNew {

  public static Workbook exportExcel(ExportParams entity, Class<?> pojoClass, Collection<?> dataSet) {
    Workbook workbook = getWorkbook(entity.getType(), dataSet.size());
    (new ExcelExportServiceNew()).createSheet(workbook, entity, pojoClass, dataSet);
    return workbook;
  }

  private static Workbook getWorkbook(ExcelType type, int size) {
    if (ExcelType.HSSF.equals(type)) {
      return new HSSFWorkbook();
    } else {
      return (Workbook)(size < 100000 ? new XSSFWorkbook() : new SXSSFWorkbook());
    }
  }
}

3. 从上面的 createSheet()方法进入ExcelExportServiceNew 类 

关于 ExcelExportServiceNew 类 ,我主要修改了createSheet方法,主要是获取注解字段,以便后面在往excel填充数据时候 根据不同的字段 设置不同样式,从而到达不同颜色字体的效果 (完整代码在末尾)。

  public void createSheet(Workbook workbook, ExportParams entity, Class<?> pojoClass, Collection<?> dataSet) {
    if (LOGGER.isDebugEnabled()) {
      LOGGER.debug("Excel export start ,class is {}", pojoClass);
      LOGGER.debug("Excel version is {}", entity.getType().equals(ExcelType.HSSF) ? "03" : "07");
    }

    if (workbook != null && entity != null && pojoClass != null && dataSet != null) {
      try {
        List<ExcelExportEntity> excelParams = new ArrayList();
        Field[] fileds = PoiPublicUtil.getClassFields(pojoClass);
        ExcelTarget etarget = (ExcelTarget)pojoClass.getAnnotation(ExcelTarget.class);

        // 根据有注解的字段设置颜色字体
        List<String> colorFieldList = new ArrayList<>();
        for(int i = 0; i < fileds.length; ++i) {
          Field field = fileds[i];
          if (field.getAnnotation(ColorFontFiled.class) != null) {
            ColorFontFiled colorFontFiled = (ColorFontFiled)field.getAnnotation(ColorFontFiled.class);
            colorFieldList.add(colorFontFiled.name());
          }
        }
        String targetId = etarget == null ? null : etarget.value();
        this.getAllExcelField(entity.getExclusions(), targetId, fileds, excelParams, pojoClass, (List)null, (ExcelEntity)null);
        // 传递注解字段进入下一步方法
        this.createSheetForMap(workbook, entity, excelParams, dataSet, colorFieldList);
      } catch (Exception var9) {
        LOGGER.error(var9.getMessage(), var9);
        throw new ExcelExportException(ExcelExportEnum.EXPORT_ERROR, var9.getCause());
      }
    } else {
      throw new ExcelExportException(ExcelExportEnum.PARAMETER_ERROR);
    }
  }

修改了上面代码后,根据createSheetForMap() 进入 insertDataToSheet()方法 最后在进入createCells时 同样传递 colorFieldList (完整代码在末尾))

 Iterator<?> its = dataSet.iterator();

      ArrayList tempList = new ArrayList();
      while(its.hasNext()) {
        Object t = its.next();
        index += this.createCells(patriarch, index, t, excelParams, sheet, workbook, rowHeight, colorFieldList);
        tempList.add(t);
        if (index >= MAX_NUM) {
          break;
        }
      }
      // 自定义样式存在Map里面,每次用完就clear
      cellStyleMap.clear();

4. 根据createCells 进入 BaseExportServiceNew类,

这个类很重要,实现不同列字体颜色就在这里实现的(完整代码在末尾)

// 创建map存excel的不同列的单元格样式
  public static Map<Integer, CellStyle> cellStyleMap = new HashMap<>();
  protected IExcelExportStylerNew excelExportStyler;

  public BaseExportServiceNew() {
    this.type = ExcelType.HSSF;
    this.statistics = new HashMap();
  }

  public int createCells(Drawing patriarch, int index, Object t, List<ExcelExportEntity> excelParams, Sheet sheet, Workbook workbook, short rowHeight, List<String> colorFieldList) {
    try {
      Row row = sheet.createRow(index);
      row.setHeight(rowHeight);
      int maxHeight = 1;
      int cellNum = 0;
      int indexKey = this.createIndexCell(row, index, (ExcelExportEntity)excelParams.get(0));
      cellNum = cellNum + indexKey;
      int k = indexKey;

      ExcelExportEntity entity;
      int paramSize;
      CellStyle cellStyle;
      for(paramSize = excelParams.size(); k < paramSize; ++k) {
        entity = (ExcelExportEntity)excelParams.get(k);
        if (entity.getList() == null) {
          Object value = this.getCellValue(entity, t);
          if (entity.getType() == BaseEntityTypeConstants.STRING_TYPE) {
            // excelParams.size代表有多少列,根据不同列,设置不同的样式
            if (ObjectUtil.isNull(cellStyleMap.get(k))) {
              if (colorFieldList.contains(entity.getName())) {
                // 设置字体样式
                cellStyle = this.getStylesColorFont(workbook, true);
              } else {
                cellStyle = this.getStylesColorFont(workbook, false);
              }
              // 用Map存对应的字体样式,
              cellStyleMap.put(k, cellStyle);
            }
            // 创建单元格
            this.createStringCell(row, cellNum++, value == null ? "" : value.toString(), index % 2 == 0 ? cellStyleMap.get(k) : cellStyleMap.get(k), entity);
            if (entity.isHyperlink()) {
              row.getCell(cellNum - 1).setHyperlink(this.dataHandler.getHyperlink(row.getSheet().getWorkbook().getCreationHelper(), t, entity.getName(), value));
            }
          }
        }
      }

      cellNum = 0;
      k = indexKey;

      for(paramSize = excelParams.size(); k < paramSize; ++k) {
        entity = (ExcelExportEntity)excelParams.get(k);
        if (entity.getList() != null) {
          cellNum += entity.getList().size();
        } else if (entity.isNeedMerge() && maxHeight > 1) {
          for(int i = index + 1; i < index + maxHeight; ++i) {
            sheet.getRow(i).createCell(cellNum);
            sheet.getRow(i).getCell(cellNum).setCellStyle(this.getStyles(false, entity));
          }

          sheet.addMergedRegion(new CellRangeAddress(index, index + maxHeight - 1, cellNum, cellNum));
          ++cellNum;
        }
      }

      return maxHeight;
    } catch (Exception var19) {
      LOGGER.error("excel cell export error ,data is :{}", ReflectionToStringBuilder.toString(t));
      throw new ExcelExportException(ExcelExportEnum.EXPORT_ERROR, var19);
    }
  }

  public CellStyle getStyles(boolean needOne, ExcelExportEntity entity) {
    return this.excelExportStyler.getStyles(needOne, entity);
  }

  // 根据不同的flag创建对应字体样式
  public CellStyle getStylesColorFont(Workbook workbook, boolean flag) {
    return this.excelExportStyler.getStylesColorFont(workbook, flag);
  }

5. IExcelExportStylerNew、ExcelExportServiceNew、BaseExportServiceNew完整代码

除了上面展示的部分是我自己修改的,下面基本上都是源代码,

关于 IExcelExportStylerNew 类

public interface IExcelExportStylerNew {

  CellStyle getHeaderStyle(short var1);

  CellStyle getTitleStyle(short var1);

  CellStyle getStylesColorFont(Workbook workbook, boolean flag);

  /** @deprecated */
  CellStyle getStyles(boolean var1, ExcelExportEntity var2);

  CellStyle getStyles(Cell var1, int var2, ExcelExportEntity var3, Object var4, Object var5);

  CellStyle getTemplateStyles(boolean var1, ExcelForEachParams var2);
}

ExcelExportServiceNew类:

public class ExcelExportServiceNew  extends BaseExportServiceNew {

  private static int MAX_NUM = 60000;

  protected int createHeaderAndTitle(ExportParams entity, Sheet sheet, Workbook workbook, List<ExcelExportEntity> excelParams) {
    int rows = 0;
    int fieldLength = this.getFieldLength(excelParams);
    if (entity.getTitle() != null) {
      rows += this.createTitle2Row(entity, sheet, workbook, fieldLength);
    }

    rows += this.createHeaderRow(entity, sheet, workbook, rows, excelParams);
    sheet.createFreezePane(0, rows, 0, rows);
    return rows;
  }

  private int createHeaderRow(ExportParams title, Sheet sheet, Workbook workbook, int index, List<ExcelExportEntity> excelParams) {
    Row row = sheet.createRow(index);
    int rows = this.getRowNums(excelParams);
    row.setHeight(title.getHeaderHeight());
    Row listRow = null;
    if (rows == 2) {
      listRow = sheet.createRow(index + 1);
      listRow.setHeight(title.getHeaderHeight());
    }

    int cellIndex = 0;
    int groupCellLength = 0;
    CellStyle titleStyle = this.getExcelExportStyler().getTitleStyle(title.getColor());
    int i = 0;

    for(int exportFieldTitleSize = excelParams.size(); i < exportFieldTitleSize; ++i) {
      ExcelExportEntity entity = (ExcelExportEntity)excelParams.get(i);
      if (StringUtils.isBlank(entity.getGroupName()) || !entity.getGroupName().equals(((ExcelExportEntity)excelParams.get(i - 1)).getGroupName())) {
        if (groupCellLength > 1) {
          sheet.addMergedRegion(new CellRangeAddress(index, index, cellIndex - groupCellLength, cellIndex - 1));
        }

        groupCellLength = 0;
      }

      if (StringUtils.isNotBlank(entity.getGroupName())) {
        this.createStringCell(row, cellIndex, entity.getGroupName(), titleStyle, entity);
        this.createStringCell(listRow, cellIndex, entity.getName(), titleStyle, entity);
        ++groupCellLength;
      } else if (StringUtils.isNotBlank(entity.getName())) {
        this.createStringCell(row, cellIndex, entity.getName(), titleStyle, entity);
      }

      if (entity.getList() == null) {
        if (rows == 2 && StringUtils.isBlank(entity.getGroupName())) {
          this.createStringCell(listRow, cellIndex, "", titleStyle, entity);
          sheet.addMergedRegion(new CellRangeAddress(index, index + 1, cellIndex, cellIndex));
        }
      } else {
        List<ExcelExportEntity> sTitel = entity.getList();
        if (StringUtils.isNotBlank(entity.getName())) {
          sheet.addMergedRegion(new CellRangeAddress(index, index, cellIndex, cellIndex + sTitel.size() - 1));
        }

        int j = 0;

        for(int size = sTitel.size(); j < size; ++j) {
          this.createStringCell(rows == 2 ? listRow : row, cellIndex, ((ExcelExportEntity)sTitel.get(j)).getName(), titleStyle, entity);
          ++cellIndex;
        }

        --cellIndex;
      }

      ++cellIndex;
    }

    if (groupCellLength > 1) {
      sheet.addMergedRegion(new CellRangeAddress(index, index, cellIndex - groupCellLength, cellIndex - 1));
    }

    return rows;
  }

  public int createTitle2Row(ExportParams entity, Sheet sheet, Workbook workbook, int fieldWidth) {
    Row row = sheet.createRow(0);
    row.setHeight(entity.getTitleHeight());
    this.createStringCell(row, 0, entity.getTitle(), this.getExcelExportStyler().getHeaderStyle(entity.getHeaderColor()), (ExcelExportEntity)null);

    for(int i = 1; i <= fieldWidth; ++i) {
      this.createStringCell(row, i, "", this.getExcelExportStyler().getHeaderStyle(entity.getHeaderColor()), (ExcelExportEntity)null);
    }

    sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, fieldWidth));
    if (entity.getSecondTitle() == null) {
      return 1;
    } else {
      row = sheet.createRow(1);
      row.setHeight(entity.getSecondTitleHeight());
      CellStyle style = workbook.createCellStyle();
      //style.setAlignment((short)3);
      this.createStringCell(row, 0, entity.getSecondTitle(), style, (ExcelExportEntity)null);

      for(int i = 1; i <= fieldWidth; ++i) {
        this.createStringCell(row, i, "", this.getExcelExportStyler().getHeaderStyle(entity.getHeaderColor()), (ExcelExportEntity)null);
      }

      sheet.addMergedRegion(new CellRangeAddress(1, 1, 0, fieldWidth));
      return 2;
    }
  }

  public void createSheet(Workbook workbook, ExportParams entity, Class<?> pojoClass, Collection<?> dataSet) {
    if (LOGGER.isDebugEnabled()) {
      LOGGER.debug("Excel export start ,class is {}", pojoClass);
      LOGGER.debug("Excel version is {}", entity.getType().equals(ExcelType.HSSF) ? "03" : "07");
    }

    if (workbook != null && entity != null && pojoClass != null && dataSet != null) {
      try {
        List<ExcelExportEntity> excelParams = new ArrayList();
        Field[] fileds = PoiPublicUtil.getClassFields(pojoClass);
        ExcelTarget etarget = (ExcelTarget)pojoClass.getAnnotation(ExcelTarget.class);

        // 根据有注解的字段设置颜色字体
        List<String> colorFieldList = new ArrayList<>();
        for(int i = 0; i < fileds.length; ++i) {
          Field field = fileds[i];
          if (field.getAnnotation(ColorFontFiled.class) != null) {
            ColorFontFiled colorFontFiled = (ColorFontFiled)field.getAnnotation(ColorFontFiled.class);
            colorFieldList.add(colorFontFiled.name());
          }
        }
        String targetId = etarget == null ? null : etarget.value();
        this.getAllExcelField(entity.getExclusions(), targetId, fileds, excelParams, pojoClass, (List)null, (ExcelEntity)null);
        // 传递注解字段进入下一步方法
        this.createSheetForMap(workbook, entity, excelParams, dataSet, colorFieldList);
      } catch (Exception var9) {
        LOGGER.error(var9.getMessage(), var9);
        throw new ExcelExportException(ExcelExportEnum.EXPORT_ERROR, var9.getCause());
      }
    } else {
      throw new ExcelExportException(ExcelExportEnum.PARAMETER_ERROR);
    }
  }

  public void createSheetForMap(Workbook workbook, ExportParams entity, List<ExcelExportEntity> entityList, Collection<?> dataSet, List<String> colorFieldList) {
    if (LOGGER.isDebugEnabled()) {
      LOGGER.debug("Excel version is {}", entity.getType().equals(ExcelType.HSSF) ? "03" : "07");
    }

    if (workbook != null && entity != null && entityList != null && dataSet != null) {
      super.type = entity.getType();
      if (this.type.equals(ExcelType.XSSF)) {
        MAX_NUM = 1000000;
      }

      if (entity.getMaxNum() > 0) {
        MAX_NUM = entity.getMaxNum();
      }

      Sheet sheet = null;

      try {
        sheet = workbook.createSheet(entity.getSheetName());
      } catch (Exception var7) {
        sheet = workbook.createSheet();
      }

      this.insertDataToSheet(workbook, entity, entityList, dataSet, sheet, colorFieldList);
    } else {
      throw new ExcelExportException(ExcelExportEnum.PARAMETER_ERROR);
    }
  }

  protected void insertDataToSheet(Workbook workbook, ExportParams entity, List<ExcelExportEntity> entityList, Collection<?> dataSet, Sheet sheet, List<String> colorFieldList) {
    try {
      this.dataHandler = entity.getDataHandler();
      if (this.dataHandler != null && this.dataHandler.getNeedHandlerFields() != null) {
        this.needHandlerList = Arrays.asList(this.dataHandler.getNeedHandlerFields());
      }

      this.dictHandler = entity.getDictHandler();
      this.setExcelExportStyler((IExcelExportStylerNew) entity.getStyle().getConstructor(Workbook.class).newInstance(workbook));
      Drawing patriarch = PoiExcelGraphDataUtil.getDrawingPatriarch(sheet);
      List<ExcelExportEntity> excelParams = new ArrayList();
      if (entity.isAddIndex()) {
        excelParams.add(this.indexExcelEntity(entity));
      }

      excelParams.addAll(entityList);
      this.sortAllParams(excelParams);
      int index = entity.isCreateHeadRows() ? this.createHeaderAndTitle(entity, sheet, workbook, excelParams) : 0;
      this.setCellWith(excelParams, sheet);
      this.setColumnHidden(excelParams, sheet);
      short rowHeight = entity.getHeight() > 0 ? entity.getHeight() : this.getRowHeight(excelParams);
      this.setCurrentIndex(1);

      Iterator<?> its = dataSet.iterator();

      ArrayList tempList = new ArrayList();
      while(its.hasNext()) {
        Object t = its.next();
        index += this.createCells(patriarch, index, t, excelParams, sheet, workbook, rowHeight, colorFieldList);
        tempList.add(t);
        if (index >= MAX_NUM) {
          break;
        }
      }
      cellStyleMap.clear();

      if (entity.getFreezeCol() != 0) {
        sheet.createFreezePane(entity.getFreezeCol(), 0, entity.getFreezeCol(), 0);
      }

      this.mergeCells(sheet, excelParams, index);
      its = dataSet.iterator();
      int i = 0;

      for(int le = tempList.size(); i < le; ++i) {
        its.next();
        its.remove();
      }

      if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("List data more than max ,data size is {}", dataSet.size());
      }

      if (dataSet.size() > 0) {
        this.createSheetForMap(workbook, entity, entityList, dataSet, colorFieldList);
      } else {
        this.addStatisticsRow(this.getExcelExportStyler().getStyles(true, (ExcelExportEntity)null), sheet);
      }

    } catch (Exception var15) {
      LOGGER.error(var15.getMessage(), var15);
      throw new ExcelExportException(ExcelExportEnum.EXPORT_ERROR, var15.getCause());
    }
  }

}

BaseExportServiceNew类

public class BaseExportServiceNew extends ExportCommonService {

  private int currentIndex = 0;
  protected ExcelType type;
  private Map<Integer, Double> statistics;
  private static final DecimalFormat DOUBLE_FORMAT = new DecimalFormat("######0.00");
  // 创建map存excel的不同列的单元格样式
  public static Map<Integer, CellStyle> cellStyleMap = new HashMap<>();
  protected IExcelExportStylerNew excelExportStyler;

  public BaseExportServiceNew() {
    this.type = ExcelType.HSSF;
    this.statistics = new HashMap();
  }

  public int createCells(Drawing patriarch, int index, Object t, List<ExcelExportEntity> excelParams, Sheet sheet, Workbook workbook, short rowHeight, List<String> colorFieldList) {
    try {
      Row row = sheet.createRow(index);
      row.setHeight(rowHeight);
      int maxHeight = 1;
      int cellNum = 0;
      int indexKey = this.createIndexCell(row, index, (ExcelExportEntity)excelParams.get(0));
      cellNum = cellNum + indexKey;
      int k = indexKey;

      ExcelExportEntity entity;
      int paramSize;
      CellStyle cellStyle;
      for(paramSize = excelParams.size(); k < paramSize; ++k) {
        entity = (ExcelExportEntity)excelParams.get(k);
        if (entity.getList() == null) {
          Object value = this.getCellValue(entity, t);
          if (entity.getType() == BaseEntityTypeConstants.STRING_TYPE) {
            // excelParams.size代表有多少列,根据不同列,设置不同的样式
            if (ObjectUtil.isNull(cellStyleMap.get(k))) {
              if (colorFieldList.contains(entity.getName())) {
                // 设置字体样式
                cellStyle = this.getStylesColorFont(workbook, true);
              } else {
                cellStyle = this.getStylesColorFont(workbook, false);
              }
              // 用Map存对应的字体样式,
              cellStyleMap.put(k, cellStyle);
            }
            // 创建单元格
            this.createStringCell(row, cellNum++, value == null ? "" : value.toString(), index % 2 == 0 ? cellStyleMap.get(k) : cellStyleMap.get(k), entity);
            if (entity.isHyperlink()) {
              row.getCell(cellNum - 1).setHyperlink(this.dataHandler.getHyperlink(row.getSheet().getWorkbook().getCreationHelper(), t, entity.getName(), value));
            }
          }
        }
      }

      cellNum = 0;
      k = indexKey;

      for(paramSize = excelParams.size(); k < paramSize; ++k) {
        entity = (ExcelExportEntity)excelParams.get(k);
        if (entity.getList() != null) {
          cellNum += entity.getList().size();
        } else if (entity.isNeedMerge() && maxHeight > 1) {
          for(int i = index + 1; i < index + maxHeight; ++i) {
            sheet.getRow(i).createCell(cellNum);
            sheet.getRow(i).getCell(cellNum).setCellStyle(this.getStyles(false, entity));
          }

          sheet.addMergedRegion(new CellRangeAddress(index, index + maxHeight - 1, cellNum, cellNum));
          ++cellNum;
        }
      }

      return maxHeight;
    } catch (Exception var19) {
      LOGGER.error("excel cell export error ,data is :{}", ReflectionToStringBuilder.toString(t));
      throw new ExcelExportException(ExcelExportEnum.EXPORT_ERROR, var19);
    }
  }

  public CellStyle getStyles(boolean needOne, ExcelExportEntity entity) {
    return this.excelExportStyler.getStyles(needOne, entity);
  }

  // 根据不同的flag创建对应字体样式
  public CellStyle getStylesColorFont(Workbook workbook, boolean flag) {
    return this.excelExportStyler.getStylesColorFont(workbook, flag);
  }

  private int createIndexCell(Row row, int index, ExcelExportEntity excelExportEntity) {
    if (excelExportEntity.getName() != null && "序号".equals(excelExportEntity.getName()) && excelExportEntity.getFormat() != null && excelExportEntity.getFormat().equals("isAddIndex")) {
      this.createStringCell(row, 0, this.currentIndex + "", index % 2 == 0 ? this.getStyles(false, (ExcelExportEntity)null) : this.getStyles(true, (ExcelExportEntity)null), (ExcelExportEntity)null);
      ++this.currentIndex;
      return 1;
    } else {
      return 0;
    }
  }



  public void createStringCell(Row row, int index, String text, CellStyle style, ExcelExportEntity entity) {
    Cell cell = row.createCell(index);
    if (style != null && style.getDataFormat() > 0 && style.getDataFormat() < 12) {
      cell.setCellValue(Double.parseDouble(text));
      //cell.setCellType(0);
    } else {
      Object rtext;
      if (this.type.equals(ExcelType.HSSF)) {
        rtext = new HSSFRichTextString(text);
      } else {
        rtext = new XSSFRichTextString(text);
      }

      cell.setCellValue((RichTextString)rtext);
    }

    // 这里是源码设置单元格样式的地方
    if (style != null) {
      cell.setCellStyle(style);
    }

    this.addStatisticsData(index, text, entity);
  }
  private void addStatisticsData(Integer index, String text, ExcelExportEntity entity) {
    if (entity != null && entity.isStatistics()) {
      Double temp = 0.0D;
      if (!this.statistics.containsKey(index)) {
        this.statistics.put(index, temp);
      }

      try {
        temp = Double.valueOf(text);
      } catch (NumberFormatException var6) {
      }

      this.statistics.put(index, (Double)this.statistics.get(index) + temp);
    }

  }

  public void createDoubleCell(Row row, int index, String text, CellStyle style, ExcelExportEntity entity) {
    Cell cell = row.createCell(index);
    if (text != null && text.length() > 0) {
      cell.setCellValue(Double.parseDouble(text));
    }

   // cell.setCellType(0);
    if (style != null) {
      cell.setCellStyle(style);
    }

    this.addStatisticsData(index, text, entity);
  }

  public void createImageCell(Drawing patriarch, ExcelExportEntity entity, Row row, int i, String imagePath, Object obj) throws Exception {
    Cell cell = row.createCell(i);
    byte[] value = null;
    if (entity.getExportImageType() != 1) {
      value = (byte[])((byte[])(entity.getMethods() != null ? this.getFieldBySomeMethod(entity.getMethods(), obj) : entity.getMethod().invoke(obj)));
    }

    this.createImageCell(cell, 50.0D * entity.getHeight(), entity.getExportImageType() == 1 ? imagePath : null, value);
  }

  public void createImageCell(Cell cell, double height, String imagePath, byte[] data) throws Exception {
    if (height > (double)cell.getRow().getHeight()) {
      cell.getRow().setHeight((short)((int)height));
    }

    Object anchor;
    if (this.type.equals(ExcelType.HSSF)) {
      anchor = new HSSFClientAnchor(0, 0, 0, 0, (short)cell.getColumnIndex(), cell.getRow().getRowNum(), (short)(cell.getColumnIndex() + 1), cell.getRow().getRowNum() + 1);
    } else {
      anchor = new XSSFClientAnchor(0, 0, 0, 0, (short)cell.getColumnIndex(), cell.getRow().getRowNum(), (short)(cell.getColumnIndex() + 1), cell.getRow().getRowNum() + 1);
    }

    if (StringUtils.isNotEmpty(imagePath)) {
      data = ImageCache.getImage(imagePath);
    }

    if (data != null) {
      PoiExcelGraphDataUtil.getDrawingPatriarch(cell.getSheet()).createPicture((ClientAnchor)anchor, cell.getSheet().getWorkbook().addPicture(data, this.getImageType(data)));
    }

  }

  public void createListCells(Drawing patriarch, int index, int cellNum, Object obj, List<ExcelExportEntity> excelParams, Sheet sheet, Workbook workbook, short rowHeight) throws Exception {
    Row row;
    if (sheet.getRow(index) == null) {
      row = sheet.createRow(index);
      row.setHeight(rowHeight);
    } else {
      row = sheet.getRow(index);
      row.setHeight(rowHeight);
    }

    int k = 0;

    for(int paramSize = excelParams.size(); k < paramSize; ++k) {
      ExcelExportEntity entity = (ExcelExportEntity)excelParams.get(k);
      Object value = this.getCellValue(entity, obj);
      if (entity.getType() == BaseEntityTypeConstants.STRING_TYPE) {
        this.createStringCell(row, cellNum++, value == null ? "" : value.toString(), row.getRowNum() % 2 == 0 ? this.getStyles(false, entity) : this.getStyles(true, entity), entity);
        if (entity.isHyperlink()) {
          row.getCell(cellNum - 1).setHyperlink(this.dataHandler.getHyperlink(row.getSheet().getWorkbook().getCreationHelper(), obj, entity.getName(), value));
        }
      } else if (entity.getType() == BaseEntityTypeConstants.DOUBLE_TYPE) {
        this.createDoubleCell(row, cellNum++, value == null ? "" : value.toString(), index % 2 == 0 ? this.getStyles(false, entity) : this.getStyles(true, entity), entity);
        if (entity.isHyperlink()) {
          row.getCell(cellNum - 1).setHyperlink(this.dataHandler.getHyperlink(row.getSheet().getWorkbook().getCreationHelper(), obj, entity.getName(), value));
        }
      } else {
        this.createImageCell(patriarch, entity, row, cellNum++, value == null ? "" : value.toString(), obj);
      }
    }

  }

  public int getImageType(byte[] value) {
    String type = PoiPublicUtil.getFileExtendName(value);
    if ("JPG".equalsIgnoreCase(type)) {
      return 5;
    } else {
      return "PNG".equalsIgnoreCase(type) ? 6 : 5;
    }
  }

  public IExcelExportStylerNew getExcelExportStyler() {
    return this.excelExportStyler;
  }

  public void setExcelExportStyler(IExcelExportStylerNew excelExportStyler) {
    this.excelExportStyler = excelExportStyler;
  }

  public void setCellWith(List<ExcelExportEntity> excelParams, Sheet sheet) {
    int index = 0;

    for(int i = 0; i < excelParams.size(); ++i) {
      if (((ExcelExportEntity)excelParams.get(i)).getList() != null) {
        List<ExcelExportEntity> list = ((ExcelExportEntity)excelParams.get(i)).getList();

        for(int j = 0; j < list.size(); ++j) {
          sheet.setColumnWidth(index, (int)(256.0D * ((ExcelExportEntity)list.get(j)).getWidth()));
          ++index;
        }
      } else {
        sheet.setColumnWidth(index, (int)(256.0D * ((ExcelExportEntity)excelParams.get(i)).getWidth()));
        ++index;
      }
    }

  }

  public void setColumnHidden(List<ExcelExportEntity> excelParams, Sheet sheet) {
    int index = 0;

    for(int i = 0; i < excelParams.size(); ++i) {
      if (((ExcelExportEntity)excelParams.get(i)).getList() != null) {
        List<ExcelExportEntity> list = ((ExcelExportEntity)excelParams.get(i)).getList();

        for(int j = 0; j < list.size(); ++j) {
          sheet.setColumnHidden(index, ((ExcelExportEntity)list.get(i)).isColumnHidden());
          ++index;
        }
      } else {
        sheet.setColumnHidden(index, ((ExcelExportEntity)excelParams.get(i)).isColumnHidden());
        ++index;
      }
    }

  }

  public void mergeCells(Sheet sheet, List<ExcelExportEntity> excelParams, int titleHeight) {
    Map<Integer, int[]> mergeMap = this.getMergeDataMap(excelParams);
    PoiMergeCellUtil.mergeCells(sheet, mergeMap, titleHeight);
  }


  private Map<Integer, int[]> getMergeDataMap(List<ExcelExportEntity> excelParams) {
    Map<Integer, int[]> mergeMap = new HashMap();
    int i = 0;
    Iterator var4 = excelParams.iterator();

    while(true) {
      while(var4.hasNext()) {
        ExcelExportEntity entity = (ExcelExportEntity)var4.next();
        if (entity.isMergeVertical()) {
          mergeMap.put(i, entity.getMergeRely());
        }

        if (entity.getList() != null) {
          for(Iterator var6 = entity.getList().iterator(); var6.hasNext(); ++i) {
            ExcelExportEntity inner = (ExcelExportEntity)var6.next();
            if (inner.isMergeVertical()) {
              mergeMap.put(i, inner.getMergeRely());
            }
          }
        } else {
          ++i;
        }
      }

      return mergeMap;
    }
  }

  public void addStatisticsRow(CellStyle styles, Sheet sheet) {
    if (this.statistics.size() > 0) {
      if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("add statistics data ,size is {}", this.statistics.size());
      }

      Row row = sheet.createRow(sheet.getLastRowNum() + 1);
      Set<Integer> keys = this.statistics.keySet();
      this.createStringCell(row, 0, "合计", styles, (ExcelExportEntity)null);
      Iterator var5 = keys.iterator();

      while(var5.hasNext()) {
        Integer key = (Integer)var5.next();
        this.createStringCell(row, key, DOUBLE_FORMAT.format(this.statistics.get(key)), styles, (ExcelExportEntity)null);
      }

      this.statistics.clear();
    }

  }

  public void setCurrentIndex(int currentIndex) {
    this.currentIndex = currentIndex;
  }


}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/510020.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

数据建模三范式说明

三范式&#xff1a; 1.原子性&#xff1a;属性不可分割 2.唯一性&#xff1a;不能存在部分依赖 3.非冗余性&#xff1a;要求任何字段不能由其他字段派生出来、确保每列都和主键列直接相关,而不是间接相关)

案例|九江银行Zabbix监控系统实践

Zabbix监控平台建设历程 九江银行Zabbix监控系统实践&#xff0c;共分为三个部分&#xff1a; 1.Zabbix监控平台的建设历程 2.Zabbix实践经验分享 3.对未来监控的展望。 项目背景 建立新的一体化基础监控平台。为适应数字化转型的需要、新技术发展的需要及业务连续性的需…

关于使用Lombok的注意事项

文章目录 1、Lombok简介2、使用Lombok的问题2.1 驼峰问题2.2 相同的字符串不同的大小写 3、关于使用Lombok的总结4、写在最后 1、Lombok简介 Lombok项目是一个Java库&#xff0c;它会自动插入您的编辑器和构建工具中&#xff0c;从而为你优化Java代码。通过注解的方式代替我们手…

注入攻击(二)--------HTML(有源码)

前序文章 注入攻击&#xff08;一&#xff09;--------SQL注入(结合BUUCTF sqli-labs) 目录 示例网站搭建1.搭建LAMP开发环境1. MySQL2. PHP3. Apache 写在示例前示例1.反射型HTML注入页面效果源码 示例2.钓鱼表单页面效果源码 示例3.存储型HTML注入页面效果源码 示例网站搭建 …

【Docker】使用 Docker 部署 Maven 仓库

在本文中&#xff0c;将介绍如何使用 Docker 部署一个 Maven 本地私服。Maven 私服可以帮助我们管理和共享本地的 Maven 依赖&#xff0c;提高开发效率。本文将使用 Sonatype Nexus 作为 Maven 私服&#xff0c;并使用 Docker Compose 来部署和管理容器。 准备工作 在开始之前…

mysql数据库在windows服务器下安装

一、mysql安装包下载 官网下载地址&#xff1a;mysql安装包下载 如图所示&#xff1a; 二、配置my.ini文件 解压后的文件尽量不要放在C盘&#xff08;内存小&#xff09;&#xff0c;解压后如下图所示 在上图所示根目录下配置my.ini文件 1、右键创建一个文本&#xff08;.text…

pikachu靶场-Unsafe Upfileupload

文件上传漏洞简述 什么是文件上传漏洞&#xff1f;  ​ 凡是存在文件上传的地方均有可能存在文件上传漏洞&#xff0c;关于上传文件操作的时候对方代码写的是否完整、是否安全&#xff0c;一旦疏忽了某个地方可能会造成文件上传漏洞。 文件上传的原理 网站Web应用都有一些文件…

1.SpringBoot基础篇

SpringBoot 文档更新日志 版本更新日期操作描述v1.02021/11/14A基础篇 前言 ​ 很荣幸有机会能以这样的形式和互联网上的各位小伙伴一起学习交流技术课程&#xff0c;这次给大家带来的是Spring家族中比较重要的一门技术课程——SpringBoot。一句话介绍这个技术&#xff0c;…

华为pbr双出口外线,指定内网单个vlan绑定单个出口外线上网

公司两条外线&#xff0c;vlan 10用nat走上面转发出去上网&#xff0c;vlan 20 走下面那条外线出去nat上网 AR2&#xff1a; interface GigabitEthernet0/0/0 ip address 6.6.6.1 255.255.255.0 interface GigabitEthernet0/0/1 ip address 154.1.2.3 255.255.255.0 interface…

Python+Selenium4环境搭建

set集合 怎么把列表种相同的数据和不同的数据取出来 1.把列表转为set集合 2.按照集合的交集 selenium 自动化测试&#xff1a;自动化测试就是通过代码或者是工具模拟人的行为来进行对WEB&#xff08;APP&#xff09;来进行操作。 QTP (HP公司)&#xff1a;以录制回放的模式…

集7大模态(视频、图片、音频、文本、深度图、热力图、惯性)的IMAGEBIND

论文&#xff1a;IMAGEBIND: One Embedding Space To Bind Them All GitHub&#xff1a;https://github.com/facebookresearch/ImageBind Meta AI 提出了 ImageBind&#xff0c;它通过利用多种类型的图像配对数据来学习单个共享表示空间。该研究不需要所有模态相互同时出现的数…

《Kubernetes证书篇:基于cfssl工具集一键生成二进制kubernetes集群相关证书(方法一)》

一、背景信息 Kubernetes 需要 PKI 证书才能进行基于 TLS 的身份验证。如果你是使用 kubeadm 安装的 Kubernetes&#xff0c; 则会自动生成集群所需的证书。如果你是使用二进制安装的 Kubernetes&#xff0c;则需要自己手动生成集群所需的证书。 1、首先从etcd算起 1、etcd CA…

百度地图绘制地区的棱柱效果-定位-自定义点-文本标记-信息弹窗

文章目录 百度地图webgl使用自定义地图样式地区镂面棱柱效果绘制点信息以及信息弹窗 百度地图webgl使用 在项目的index.html中引入 <script type"text/javascript" src"//api.map.baidu.com/api?typewebgl&v1.0&ak你的AK秘钥"></script…

花式反转字符串

文章目录 简单反转字符串题目详情分析Java完整代码 反转链表进阶问题题目详情分析Java完整代码 左旋转字符串题目详情分析Java完整代码 反转字符串中的单词题目详情分析Java完整代码 本文对常见的反转字符串题目进行串烧整理。 简单反转字符串 题目详情 编写一个函数&#xf…

9. 对象指针与对象数组

一、对象指针 声明形式&#xff1a; 类名 *对象指针名; Clock c(8, 3, 10); Clock *ptr; ptr &c;通过指针访问对象成员&#xff08;一般类的属性都是封装起来的&#xff0c;因此通常是通过指针访问成员函数&#xff09; 对象指针名->成员名 ptr->getHour();相当于(*…

linux0.12-8-7-signal.c

[334页] (-:这一小节很难理解。但我基本都理解了&#xff0c;哈哈。 1、为什么signal不可靠&#xff0c;而sigaction可靠&#xff1b; 2、 为什么系统调用会被打断&#xff1f; 3、 sys_signal&#xff0c;sys_sigaction&#xff0c;函数作用&#xff1f; 4、 do_signal&#x…

【高项】高级项目管理与组织管理(第4版教材第20-23章,管理科学知识)

文章目录 【高项系列】知识复习1、高级项目管理&#xff08;组织级管理&#xff0c;项目集管理&#xff0c;项目组合管理&#xff0c;量化项目管理&#xff0c;项目成熟度模型&#xff09;1.1 组织级项目管理&#xff08;项目组合项目集, 战略方向一致&#xff0c;0-1分&#x…

python并发编程:并发编程中是选择多线程呢?还是多进程呢?还是多协程呢?

❝ Python对并发编程的支持非常丰富&#xff0c;可以使用多线程、多进程、协程等方式进行并发编程。那么&#xff0c;应该如何选择呢&#xff1f; ❞ Python并发编程有哪些方式 Python并发编程有三种方式: 多线程 Thread 多进程 Process 多协程 Coroutine 什么是CPU密集型计算、…

《花雕学AI》Poe 一站式 AI 工具箱:ChatGPT4 体验邀请,亲,不要错过哦!

你有没有想过&#xff0c;如果你能在同一个平台上体验多种不同的 AI 模型&#xff0c;和他们进行有趣、有用、有深度的对话&#xff0c;甚至还能轻松地分享你的对话给其他人&#xff0c;那该有多好&#xff1f;如果你有这样的想法&#xff0c;那么你一定不能错过 Poe 一站式 AI…

winsows10 下 wsl2 使用 rviz 报错 Segmentation fault 段错误 (核心已转储) 的另一可能解决方案

问题 今天在 wsl 里使用 rviz 时突然报错 Segmentation fault 无法使用了, 报错如下 (base) rootXAIR14:~ $ rviz QStandardPaths: XDG_RUNTIME_DIR not set, defaulting to /tmp/runtime-root [ INFO] [1683702959.671174856]: rviz version 1.13.29 [ INFO] [1683702959.67…