Search in sources :

Example 16 with WriteCellStyle

use of com.alibaba.excel.write.metadata.style.WriteCellStyle in project easyexcel by alibaba.

the class WriteTest method handlerStyleWrite.

/**
 * 拦截器形式自定义样式
 * <p>
 * 1. 创建excel对应的实体对象 参照{@link DemoData}
 * <p>
 * 2. 创建一个style策略 并注册
 * <p>
 * 3. 直接写即可
 */
@Test
public void handlerStyleWrite() {
    // 方法1 使用已有的策略 推荐
    // HorizontalCellStyleStrategy 每一行的样式都一样 或者隔行一样
    // AbstractVerticalCellStyleStrategy 每一列的样式都一样 需要自己回调每一页
    String fileName = TestFileUtil.getPath() + "handlerStyleWrite" + System.currentTimeMillis() + ".xlsx";
    // 头的策略
    WriteCellStyle headWriteCellStyle = new WriteCellStyle();
    // 背景设置为红色
    headWriteCellStyle.setFillForegroundColor(IndexedColors.RED.getIndex());
    WriteFont headWriteFont = new WriteFont();
    headWriteFont.setFontHeightInPoints((short) 20);
    headWriteCellStyle.setWriteFont(headWriteFont);
    // 内容的策略
    WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
    // 这里需要指定 FillPatternType 为FillPatternType.SOLID_FOREGROUND 不然无法显示背景颜色.头默认了 FillPatternType所以可以不指定
    contentWriteCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
    // 背景绿色
    contentWriteCellStyle.setFillForegroundColor(IndexedColors.GREEN.getIndex());
    WriteFont contentWriteFont = new WriteFont();
    // 字体大小
    contentWriteFont.setFontHeightInPoints((short) 20);
    contentWriteCellStyle.setWriteFont(contentWriteFont);
    // 这个策略是 头是头的样式 内容是内容的样式 其他的策略可以自己实现
    HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
    // 这里 需要指定写用哪个class去写,然后写到第一个sheet,名字为模板 然后文件流会自动关闭
    EasyExcel.write(fileName, DemoData.class).registerWriteHandler(horizontalCellStyleStrategy).sheet("模板").doWrite(data());
    // 方法2: 使用easyexcel的方式完全自己写 不太推荐 尽量使用已有策略
    // @since 3.0.0-beta2
    fileName = TestFileUtil.getPath() + "handlerStyleWrite" + System.currentTimeMillis() + ".xlsx";
    EasyExcel.write(fileName, DemoData.class).registerWriteHandler(new CellWriteHandler() {

        @Override
        public void afterCellDispose(CellWriteHandlerContext context) {
            // 判断不是头的情况 如果是fill 的情况 这里会==null 所以用not true
            if (BooleanUtils.isNotTrue(context.getHead())) {
                // 第一个单元格
                // 只要不是头 一定会有数据 当然fill的情况 可能要context.getCellDataList() ,这个需要看模板,因为一个单元格会有多个 WriteCellData
                WriteCellData<?> cellData = context.getFirstCellData();
                // 这里需要去cellData 获取样式
                // 很重要的一个原因是 WriteCellStyle 和 dataFormatData绑定的 简单的说 比如你加了 DateTimeFormat
                // ,已经将writeCellStyle里面的dataFormatData 改了 如果你自己new了一个WriteCellStyle,可能注解的样式就失效了
                // 然后 getOrCreateStyle 用于返回一个样式,如果为空,则创建一个后返回
                WriteCellStyle writeCellStyle = cellData.getOrCreateStyle();
                writeCellStyle.setFillForegroundColor(IndexedColors.RED.getIndex());
                // 这里需要指定 FillPatternType 为FillPatternType.SOLID_FOREGROUND
                writeCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
            // 这样样式就设置好了 后面有个FillStyleCellWriteHandler 默认会将 WriteCellStyle 设置到 cell里面去 所以可以不用管了
            }
        }
    }).sheet("模板").doWrite(data());
    // 方法3: 使用poi的样式完全自己写 不推荐
    // @since 3.0.0-beta2
    // 坑1:style里面有dataformat 用来格式化数据的 所以自己设置可能导致格式化注解不生效
    // 坑2:不要一直去创建style 记得缓存起来 最多创建6W个就挂了
    fileName = TestFileUtil.getPath() + "handlerStyleWrite" + System.currentTimeMillis() + ".xlsx";
    EasyExcel.write(fileName, DemoData.class).registerWriteHandler(new CellWriteHandler() {

        @Override
        public void afterCellDispose(CellWriteHandlerContext context) {
            // 判断不是头的情况 如果是fill 的情况 这里会==null 所以用not true
            if (BooleanUtils.isNotTrue(context.getHead())) {
                Cell cell = context.getCell();
                // 拿到poi的workbook
                Workbook workbook = context.getWriteWorkbookHolder().getWorkbook();
                // 这里千万记住 想办法能复用的地方把他缓存起来 一个表格最多创建6W个样式
                // 不同单元格尽量传同一个 cellStyle
                CellStyle cellStyle = workbook.createCellStyle();
                cellStyle.setFillForegroundColor(IndexedColors.RED.getIndex());
                // 这里需要指定 FillPatternType 为FillPatternType.SOLID_FOREGROUND
                cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
                cell.setCellStyle(cellStyle);
                // 由于这里没有指定dataformat 最后展示的数据 格式可能会不太正确
                // 这里要把 WriteCellData的样式清空, 不然后面还有一个拦截器 FillStyleCellWriteHandler 默认会将 WriteCellStyle 设置到
                // cell里面去 会导致自己设置的不一样
                context.getFirstCellData().setWriteCellStyle(null);
            }
        }
    }).sheet("模板").doWrite(data());
}
Also used : WriteCellData(com.alibaba.excel.metadata.data.WriteCellData) CellWriteHandlerContext(com.alibaba.excel.write.handler.context.CellWriteHandlerContext) WriteCellStyle(com.alibaba.excel.write.metadata.style.WriteCellStyle) CellWriteHandler(com.alibaba.excel.write.handler.CellWriteHandler) WriteFont(com.alibaba.excel.write.metadata.style.WriteFont) WriteCellStyle(com.alibaba.excel.write.metadata.style.WriteCellStyle) CellStyle(org.apache.poi.ss.usermodel.CellStyle) Cell(org.apache.poi.ss.usermodel.Cell) Workbook(org.apache.poi.ss.usermodel.Workbook) HorizontalCellStyleStrategy(com.alibaba.excel.write.style.HorizontalCellStyleStrategy) Test(org.junit.Test)

Example 17 with WriteCellStyle

use of com.alibaba.excel.write.metadata.style.WriteCellStyle in project easyexcel by alibaba.

the class StyleDataTest method t04AbstractVerticalCellStyleStrategy02.

@Test
public void t04AbstractVerticalCellStyleStrategy02() {
    final StyleProperty styleProperty = StyleProperty.build(StyleData.class.getAnnotation(HeadStyle.class));
    final FontProperty fontProperty = FontProperty.build(StyleData.class.getAnnotation(HeadFontStyle.class));
    AbstractVerticalCellStyleStrategy verticalCellStyleStrategy = new AbstractVerticalCellStyleStrategy() {

        @Override
        protected WriteCellStyle headCellStyle(Head head) {
            WriteCellStyle writeCellStyle = WriteCellStyle.build(styleProperty, fontProperty);
            if (head.getColumnIndex() == 0) {
                writeCellStyle.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
                WriteFont writeFont = new WriteFont();
                writeFont.setItalic(true);
                writeFont.setStrikeout(true);
                writeFont.setTypeOffset(Font.SS_NONE);
                writeFont.setUnderline(Font.U_DOUBLE);
                writeFont.setBold(true);
                writeFont.setCharset((int) Font.DEFAULT_CHARSET);
            } else {
                writeCellStyle.setFillForegroundColor(IndexedColors.BLUE.getIndex());
            }
            return writeCellStyle;
        }

        @Override
        protected WriteCellStyle contentCellStyle(Head head) {
            WriteCellStyle writeCellStyle = new WriteCellStyle();
            writeCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
            if (head.getColumnIndex() == 0) {
                writeCellStyle.setFillForegroundColor(IndexedColors.DARK_GREEN.getIndex());
            } else {
                writeCellStyle.setFillForegroundColor(IndexedColors.PINK.getIndex());
            }
            return writeCellStyle;
        }
    };
    EasyExcel.write(fileVerticalCellStyleStrategy207, StyleData.class).registerWriteHandler(verticalCellStyleStrategy).sheet().doWrite(data());
}
Also used : StyleProperty(com.alibaba.excel.metadata.property.StyleProperty) FontProperty(com.alibaba.excel.metadata.property.FontProperty) AbstractVerticalCellStyleStrategy(com.alibaba.excel.write.style.AbstractVerticalCellStyleStrategy) Head(com.alibaba.excel.metadata.Head) WriteCellStyle(com.alibaba.excel.write.metadata.style.WriteCellStyle) WriteFont(com.alibaba.excel.write.metadata.style.WriteFont) HeadFontStyle(com.alibaba.excel.annotation.write.style.HeadFontStyle) HeadStyle(com.alibaba.excel.annotation.write.style.HeadStyle) Test(org.junit.Test)

Example 18 with WriteCellStyle

use of com.alibaba.excel.write.metadata.style.WriteCellStyle in project easyexcel by alibaba.

the class StyleDataTest method readAndWrite.

private void readAndWrite(File file) throws Exception {
    SimpleColumnWidthStyleStrategy simpleColumnWidthStyleStrategy = new SimpleColumnWidthStyleStrategy(50);
    SimpleRowHeightStyleStrategy simpleRowHeightStyleStrategy = new SimpleRowHeightStyleStrategy((short) 40, (short) 50);
    WriteCellStyle headWriteCellStyle = new WriteCellStyle();
    headWriteCellStyle.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
    WriteFont headWriteFont = new WriteFont();
    headWriteFont.setFontHeightInPoints((short) 20);
    headWriteFont.setColor(IndexedColors.DARK_YELLOW.getIndex());
    headWriteCellStyle.setWriteFont(headWriteFont);
    WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
    contentWriteCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
    contentWriteCellStyle.setFillForegroundColor(IndexedColors.TEAL.getIndex());
    WriteFont contentWriteFont = new WriteFont();
    contentWriteFont.setFontHeightInPoints((short) 30);
    contentWriteFont.setColor(IndexedColors.DARK_TEAL.getIndex());
    contentWriteCellStyle.setWriteFont(contentWriteFont);
    HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
    OnceAbsoluteMergeStrategy onceAbsoluteMergeStrategy = new OnceAbsoluteMergeStrategy(2, 2, 0, 1);
    EasyExcel.write(file, StyleData.class).registerWriteHandler(simpleColumnWidthStyleStrategy).registerWriteHandler(simpleRowHeightStyleStrategy).registerWriteHandler(horizontalCellStyleStrategy).registerWriteHandler(onceAbsoluteMergeStrategy).sheet().doWrite(data());
    EasyExcel.read(file, StyleData.class, new StyleDataListener()).sheet().doRead();
    Workbook workbook = WorkbookFactory.create(file);
    Sheet sheet = workbook.getSheetAt(0);
    Assert.assertEquals(50 * 256, sheet.getColumnWidth(0), 0);
    Row row0 = sheet.getRow(0);
    Assert.assertEquals(800, row0.getHeight(), 0);
    Cell cell00 = row0.getCell(0);
    Assert.assertArrayEquals(new byte[] { -1, -1, 0 }, StyleTestUtils.getFillForegroundColor(cell00));
    Assert.assertArrayEquals(new byte[] { -128, -128, 0 }, StyleTestUtils.getFontColor(cell00, workbook));
    Assert.assertEquals(20, StyleTestUtils.getFontHeightInPoints(cell00, workbook));
    Cell cell01 = row0.getCell(1);
    Assert.assertArrayEquals(new byte[] { -1, -1, 0 }, StyleTestUtils.getFillForegroundColor(cell01));
    Assert.assertArrayEquals(new byte[] { -128, -128, 0 }, StyleTestUtils.getFontColor(cell01, workbook));
    Assert.assertEquals(20, StyleTestUtils.getFontHeightInPoints(cell01, workbook));
    Row row1 = sheet.getRow(1);
    Assert.assertEquals(1000, row1.getHeight(), 0);
    Cell cell10 = row1.getCell(0);
    Assert.assertArrayEquals(new byte[] { 0, -128, -128 }, StyleTestUtils.getFillForegroundColor(cell10));
    Assert.assertArrayEquals(new byte[] { 0, 51, 102 }, StyleTestUtils.getFontColor(cell10, workbook));
    Assert.assertEquals(30, StyleTestUtils.getFontHeightInPoints(cell10, workbook));
    Cell cell11 = row1.getCell(1);
    Assert.assertArrayEquals(new byte[] { 0, -128, -128 }, StyleTestUtils.getFillForegroundColor(cell11));
    Assert.assertArrayEquals(new byte[] { 0, 51, 102 }, StyleTestUtils.getFontColor(cell11, workbook));
    Assert.assertEquals(30, StyleTestUtils.getFontHeightInPoints(cell11, workbook));
}
Also used : WriteCellStyle(com.alibaba.excel.write.metadata.style.WriteCellStyle) OnceAbsoluteMergeStrategy(com.alibaba.excel.write.merge.OnceAbsoluteMergeStrategy) WriteFont(com.alibaba.excel.write.metadata.style.WriteFont) SimpleRowHeightStyleStrategy(com.alibaba.excel.write.style.row.SimpleRowHeightStyleStrategy) Row(org.apache.poi.ss.usermodel.Row) Sheet(org.apache.poi.ss.usermodel.Sheet) Cell(org.apache.poi.ss.usermodel.Cell) Workbook(org.apache.poi.ss.usermodel.Workbook) SimpleColumnWidthStyleStrategy(com.alibaba.excel.write.style.column.SimpleColumnWidthStyleStrategy) HorizontalCellStyleStrategy(com.alibaba.excel.write.style.HorizontalCellStyleStrategy)

Aggregations

WriteCellStyle (com.alibaba.excel.write.metadata.style.WriteCellStyle)18 WriteFont (com.alibaba.excel.write.metadata.style.WriteFont)14 HorizontalCellStyleStrategy (com.alibaba.excel.write.style.HorizontalCellStyleStrategy)10 Test (org.junit.Test)8 Head (com.alibaba.excel.metadata.Head)4 AbstractVerticalCellStyleStrategy (com.alibaba.excel.write.style.AbstractVerticalCellStyleStrategy)4 CellStyle (org.apache.poi.ss.usermodel.CellStyle)4 CellWriteHandlerContext (com.alibaba.excel.write.handler.context.CellWriteHandlerContext)3 ExcelWriter (com.alibaba.excel.ExcelWriter)2 WriteCellData (com.alibaba.excel.metadata.data.WriteCellData)2 WriteSheet (com.alibaba.excel.write.metadata.WriteSheet)2 ArrayList (java.util.ArrayList)2 Cell (org.apache.poi.ss.usermodel.Cell)2 Workbook (org.apache.poi.ss.usermodel.Workbook)2 DemoData (com.alibaba.easyexcel.test.demo.write.DemoData)1 HeadFontStyle (com.alibaba.excel.annotation.write.style.HeadFontStyle)1 HeadStyle (com.alibaba.excel.annotation.write.style.HeadStyle)1 CommentData (com.alibaba.excel.metadata.data.CommentData)1 DataFormatData (com.alibaba.excel.metadata.data.DataFormatData)1 FormulaData (com.alibaba.excel.metadata.data.FormulaData)1