Selaa lähdekoodia

扩展tools-poi,为ExcelWriter增加设置单元格样式方法

Signed-off-by: luoshi <luoshi@qmth.com.cn>
luoshi 1 vuosi sitten
vanhempi
commit
194fd72c55

+ 31 - 1
tools-poi/src/main/java/com/qmth/boot/tools/excel/ExcelWriter.java

@@ -173,10 +173,40 @@ public abstract class ExcelWriter {
 
     protected abstract Workbook getWorkbook();
 
-    private CellStyle createCellStyle() {
+    /**
+     * 完成数据写入后,附加进行单元格样式设置
+     *
+     * @param sheetName    sheet名称
+     * @param style        单元格样式,通过createCellStyle方法创建
+     * @param rowNumber    行号,最小行号为0
+     * @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);
+        }
+    }
+
+    /**
+     * 创建单元格样式对象,若需要设置字体样式,通过createFont方法创建
+     *
+     * @return
+     */
+    public CellStyle createCellStyle() {
         return getWorkbook().createCellStyle();
     }
 
+    /**
+     * 创建字体样式对象,用于设置单元格样式
+     *
+     * @return
+     */
+    public Font createFont() {
+        return getWorkbook().createFont();
+    }
+
     public void output(OutputStream ous) throws IOException {
         getWorkbook().write(ous);
     }

+ 14 - 0
tools-poi/src/test/java/com/qmth/boot/test/tools/excel/write/ExcelWriteTest.java

@@ -4,6 +4,10 @@ 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.poi.ss.usermodel.CellStyle;
+import org.apache.poi.ss.usermodel.FillPatternType;
+import org.apache.poi.ss.usermodel.Font;
+import org.apache.poi.ss.usermodel.IndexedColors;
 import org.junit.Assert;
 import org.junit.Test;
 
@@ -27,6 +31,16 @@ public class ExcelWriteTest {
         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);
+        font.setFontHeightInPoints((short) 20);
+        cellStyle.setFillForegroundColor(IndexedColors.GREY_40_PERCENT.index);
+        cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
+        cellStyle.setFont(font);
+        writer.setCellStyle("sheet1", cellStyle, 0, 0);
+        writer.setCellStyle("sheet1", cellStyle, 1, 1, 2);
         writer.output(ous);
         Assert.assertTrue(ous.toByteArray().length > 0);
     }