依赖
org.apache.poi
poi-ooxml
4.1.2
代码
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);
}
}
}