Java POI 实现 Excel 交替行颜色循环?

Java 如何实现用 POI 输出 Excel 的时候,设置背景 n 行有色,n 行无色,按顺序循环下去,怎么搞呢?

阅读 930
2 个回答

依赖

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>4.1.2</version>
</dependency>

代码

package cn.haoyitec.transfer;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileOutputStream;

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

        try (Workbook workbook = new XSSFWorkbook();
             FileOutputStream outputStream = new FileOutputStream("output.xlsx")) {
            Sheet sheet = workbook.createSheet("Sheet1");

            short indexedColor = IndexedColors.RED.getIndex();
            int rowCount = 0;

            while (rowCount != 100) {
                Row row = sheet.createRow(rowCount);

                CellStyle style = workbook.createCellStyle();
                if (rowCount % 2 == 0) {
                    style.setFillForegroundColor(indexedColor);
                }
                style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
                row.setRowStyle(style);

                rowCount++;
            }

            workbook.write(outputStream);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
Workbook wb = new Workbook();
IWorksheet sheet = wb.getWorksheets().get(0);

int n = 5;
for (int row = 1; row <= 100; row += 2 * n) {
    sheet.getRange(row + ":" + (row + n - 1)).getInterior().setColor(Color.GetLightGreen());
}

wb.save("output/Background.xlsx");

实现效果:
image.png

参考链接:https://demo.grapecity.com.cn/documents-api-excel-java/demos/

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏