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

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


回答:

依赖

<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");

实现效果:

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

以上是 Java POI 实现 Excel 交替行颜色循环? 的全部内容, 来源链接: utcz.com/p/945445.html

回到顶部