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

您所在的位置:网站首页 竖着写的书名号怎么写图片 EasyPoi导出,设置不同列的字体颜色(修改easypoi 3.1.0版本源码)

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

2023-06-17 06:02| 来源: 网络整理| 查看: 265

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

和其他依赖

org.projectlombok lombok 1.18.16

需求人员要求对导出的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 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 excelParams = new ArrayList(); Field[] fileds = PoiPublicUtil.getClassFields(pojoClass); ExcelTarget etarget = (ExcelTarget)pojoClass.getAnnotation(ExcelTarget.class); // 根据有注解的字段设置颜色字体 List 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 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 excelParams, Sheet sheet, Workbook workbook, short rowHeight, List 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 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 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 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 dataSet, List 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 entityList, Collection dataSet, Sheet sheet, List 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 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 statistics; private static final DecimalFormat DOUBLE_FORMAT = new DecimalFormat("######0.00"); // 创建map存excel的不同列的单元格样式 public static Map 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 excelParams, Sheet sheet, Workbook workbook, short rowHeight, List 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 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 excelParams, Sheet sheet) { int index = 0; for(int i = 0; i < excelParams.size(); ++i) { if (((ExcelExportEntity)excelParams.get(i)).getList() != null) { List 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 excelParams, Sheet sheet) { int index = 0; for(int i = 0; i < excelParams.size(); ++i) { if (((ExcelExportEntity)excelParams.get(i)).getList() != null) { List 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 excelParams, int titleHeight) { Map mergeMap = this.getMergeDataMap(excelParams); PoiMergeCellUtil.mergeCells(sheet, mergeMap, titleHeight); } private Map getMergeDataMap(List excelParams) { Map 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 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; } }



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3