Преглед на файлове

Merge branch 'dev_20240926_poifix' into release_1.0.5

luoshi преди 8 месеца
родител
ревизия
a19a8efe25

+ 34 - 7
tools-poi/src/main/java/com/qmth/boot/tools/excel/ExcelWriter.java

@@ -3,6 +3,7 @@ package com.qmth.boot.tools.excel;
 import com.qmth.boot.tools.excel.convertor.ValueConvertor;
 import com.qmth.boot.tools.excel.convertor.ValueConvertors;
 import com.qmth.boot.tools.excel.enums.ExcelType;
+import com.qmth.boot.tools.excel.model.CellStyleConfig;
 import com.qmth.boot.tools.excel.model.DataMap;
 import com.qmth.boot.tools.excel.model.FieldParam;
 import com.qmth.boot.tools.excel.model.ObjectParam;
@@ -19,6 +20,8 @@ import java.util.concurrent.atomic.AtomicInteger;
 
 public abstract class ExcelWriter {
 
+    private CellStyleConfig styleConfig = new CellStyleConfig();
+
     /**
      * 初始化带表头的Excel生成工具
      *
@@ -107,8 +110,13 @@ public abstract class ExcelWriter {
                 Row row = sheet.createRow(rowIndex.getAndIncrement());
                 Cell cell = row.createCell(0);
                 cell.setCellValue(title);
-                CellStyle style = getWorkbook().createCellStyle();
-                style.setAlignment(HorizontalAlignment.CENTER);
+                //尝试获取预设单元格样式
+                CellStyle style = styleConfig.getStyle(sheet.getSheetName(), row.getRowNum(), cell.getColumnIndex());
+                if (style == null) {
+                    //未预设时按照默认样式设置
+                    style = getWorkbook().createCellStyle();
+                    style.setAlignment(HorizontalAlignment.CENTER);
+                }
                 cell.setCellStyle(style);
                 //根据表头宽度合并单元格
                 if (columnCount > 1) {
@@ -124,6 +132,11 @@ public abstract class ExcelWriter {
         for (String name : names) {
             Cell cell = columnNameRow.createCell(columnIndex++);
             cell.setCellValue(name);
+            //尝试获取预设单元格样式
+            CellStyle style = styleConfig.getStyle(sheet.getSheetName(), cell.getRowIndex(), cell.getColumnIndex());
+            if (style != null) {
+                cell.setCellStyle(style);
+            }
         }
     }
 
@@ -133,6 +146,11 @@ public abstract class ExcelWriter {
         for (String name : objectParam.getColumnNames()) {
             Cell cell = dataRow.createCell(columnIndex++);
             writeCell(cell, object, objectParam.get(name));
+            //尝试获取预设单元格样式
+            CellStyle style = styleConfig.getStyle(sheet.getSheetName(), cell.getRowIndex(), cell.getColumnIndex());
+            if (style != null) {
+                cell.setCellStyle(style);
+            }
         }
     }
 
@@ -142,6 +160,11 @@ public abstract class ExcelWriter {
         for (String name : columnNames) {
             Cell cell = dataRow.createCell(columnIndex++);
             cell.setCellValue(dataMap.getOrDefault(name, StringUtils.EMPTY));
+            //尝试获取预设单元格样式
+            CellStyle style = styleConfig.getStyle(sheet.getSheetName(), cell.getRowIndex(), cell.getColumnIndex());
+            if (style != null) {
+                cell.setCellStyle(style);
+            }
         }
     }
 
@@ -150,6 +173,11 @@ public abstract class ExcelWriter {
         for (int columnIndex = 0; columnIndex < columnNames.length; columnIndex++) {
             Cell cell = dataRow.createCell(columnIndex);
             cell.setCellValue(data.length > columnIndex ? data[columnIndex] : StringUtils.EMPTY);
+            //尝试获取预设单元格样式
+            CellStyle style = styleConfig.getStyle(sheet.getSheetName(), cell.getRowIndex(), cell.getColumnIndex());
+            if (style != null) {
+                cell.setCellStyle(style);
+            }
         }
     }
 
@@ -174,7 +202,7 @@ public abstract class ExcelWriter {
     protected abstract Workbook getWorkbook();
 
     /**
-     * 完成数据写入后,附加进行单元格样式设置
+     * 在数据写入前预先进行单元格样式设置
      *
      * @param sheetName    sheet名称
      * @param style        单元格样式,通过createCellStyle方法创建
@@ -182,11 +210,10 @@ public abstract class ExcelWriter {
      * @param columnIndexs 列序号数组,最小序号为0
      */
     public void setCellStyle(String sheetName, CellStyle style, int rowNumber, int... columnIndexs) {
-        Sheet sheet = getWorkbook().getSheet(sheetName);
-        for (int columnIndex : columnIndexs) {
-            Cell cell = sheet.getRow(rowNumber).getCell(columnIndex);
-            cell.setCellStyle(style);
+        if (columnIndexs == null || columnIndexs.length == 0) {
+            throw new IllegalArgumentException("columnIndexs should not be empty");
         }
+        styleConfig.addCellStyle(sheetName, rowNumber, columnIndexs, style);
     }
 
     /**

+ 64 - 0
tools-poi/src/main/java/com/qmth/boot/tools/excel/model/CellStyleConfig.java

@@ -0,0 +1,64 @@
+package com.qmth.boot.tools.excel.model;
+
+import org.apache.poi.ss.usermodel.CellStyle;
+
+import java.util.*;
+import java.util.stream.Collectors;
+
+public class CellStyleConfig {
+
+    private static final List<ConfigItem> emptyList = new ArrayList<>();
+
+    private Map<String, List<ConfigItem>> sheetItems;
+
+    public CellStyleConfig() {
+        this.sheetItems = new HashMap<>();
+    }
+
+    public void addCellStyle(String sheetName, int rowNumber, int[] columnIndex, CellStyle style) {
+        ConfigItem item = new ConfigItem();
+        item.setRowNumber(rowNumber);
+        item.setColumnIndexs(columnIndex);
+        item.setStyle(style);
+        sheetItems.computeIfAbsent(sheetName, k -> new LinkedList<>()).add(item);
+    }
+
+    public CellStyle getStyle(String sheetName, int rowNumber, int columnIndex) {
+        return sheetItems.getOrDefault(sheetName, emptyList).stream()
+                .filter(i -> i.getRowNumber() == rowNumber && i.getColumnIndexs().contains(columnIndex)).findFirst()
+                .orElse(new ConfigItem()).getStyle();
+    }
+
+    private class ConfigItem {
+
+        private int rowNumber;
+
+        private Set<Integer> columnIndexs;
+
+        private CellStyle style;
+
+        public int getRowNumber() {
+            return rowNumber;
+        }
+
+        public void setRowNumber(int rowNumber) {
+            this.rowNumber = rowNumber;
+        }
+
+        public Set<Integer> getColumnIndexs() {
+            return columnIndexs;
+        }
+
+        public void setColumnIndexs(int[] columnIndexs) {
+            this.columnIndexs = Arrays.stream(columnIndexs).boxed().collect(Collectors.toSet());
+        }
+
+        public CellStyle getStyle() {
+            return style;
+        }
+
+        public void setStyle(CellStyle style) {
+            this.style = style;
+        }
+    }
+}

+ 22 - 11
tools-poi/src/test/java/com/qmth/boot/test/tools/excel/write/ExcelWriteTest.java

@@ -4,6 +4,7 @@ import com.qmth.boot.test.tools.excel.model.ExcelTestEntity;
 import com.qmth.boot.test.tools.excel.model.GenderEnum;
 import com.qmth.boot.tools.excel.ExcelWriter;
 import com.qmth.boot.tools.excel.enums.ExcelType;
+import org.apache.commons.lang3.RandomStringUtils;
 import org.apache.poi.ss.usermodel.CellStyle;
 import org.apache.poi.ss.usermodel.FillPatternType;
 import org.apache.poi.ss.usermodel.Font;
@@ -15,23 +16,24 @@ import java.io.ByteArrayOutputStream;
 import java.io.IOException;
 import java.util.Collections;
 import java.util.Date;
+import java.util.LinkedList;
+import java.util.List;
 
 public class ExcelWriteTest {
 
     @Test
     public void testXlsx() throws IOException {
-        ExcelTestEntity entity = new ExcelTestEntity();
-        entity.setId(System.currentTimeMillis());
-        entity.setName("name");
-        entity.setScore(95.5);
-        entity.setGender(GenderEnum.FEMALE);
-        entity.setTime(new Date());
-        entity.setEnable(true);
+        //        ExcelTestEntity entity = new ExcelTestEntity();
+        //        entity.setId(System.currentTimeMillis());
+        //        entity.setName("name");
+        //        entity.setScore(95.5);
+        //        entity.setGender(GenderEnum.FEMALE);
+        //        entity.setTime(new Date());
+        //        entity.setEnable(true);
         ByteArrayOutputStream ous = new ByteArrayOutputStream();
+        //FileOutputStream ous = new FileOutputStream(new File("/Users/luoshi/Downloads/test.xlsx"));
         ExcelWriter writer = ExcelWriter.create(ExcelType.XLSX);
-        writer.writeObjects("sheet1", new String[] { "标题" }, ExcelTestEntity.class,
-                Collections.singletonList(entity).iterator());
-
+        //
         CellStyle cellStyle = writer.createCellStyle();
         Font font = writer.createFont();
         font.setColor(IndexedColors.RED.index);
@@ -40,9 +42,18 @@ public class ExcelWriteTest {
         cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
         cellStyle.setFont(font);
         writer.setCellStyle("sheet1", cellStyle, 0, 0);
-        writer.setCellStyle("sheet1", cellStyle, 1, 1, 2);
+        writer.setCellStyle("sheet1", cellStyle, 1, 0, 1);
+        //        writer.writeObjects("sheet1", new String[] { "标题" }, ExcelTestEntity.class,
+        //                Collections.singletonList(entity).iterator());
+        List<String[]> dataList = new LinkedList<>();
+        for (int i = 0; i < 10000; i++) {
+            dataList.add(
+                    new String[] { RandomStringUtils.random(8, true, true), RandomStringUtils.random(16, true, true) });
+        }
+        writer.writeDataArrays("sheet1", new String[] { "考生表" }, new String[] { "编号", "姓名" }, dataList.iterator());
         writer.output(ous);
         Assert.assertTrue(ous.toByteArray().length > 0);
+        ous.close();
     }
 
     @Test