org.apache.poi 设置背景颜色
时间: 2023-09-11 20:08:30 浏览: 71
对于使用 Apache POI 库设置单元格的背景颜色,可以使用 CellStyle 和 IndexedColors 类来实现。下面是一个示例代码:
```java
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class SetCellBackgroundColorExample {
public static void main(String[] args) {
// 创建工作簿和工作表
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Sheet1");
// 创建单元格样式
CellStyle style = workbook.createCellStyle();
// 设置背景颜色为黄色
style.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
// 创建单元格并应用样式
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("Hello, World!");
cell.setCellStyle(style);
// 保存工作簿
try {
FileOutputStream fileOut = new FileOutputStream("workbook.xlsx");
workbook.write(fileOut);
fileOut.close();
workbook.close();
System.out.println("Excel 文件生成成功!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
这段代码创建了一个包含一个单元格的 Excel 文件,并将该单元格的背景颜色设置为黄色。你可以根据需要修改代码来适应你的具体情况。记得要导入 Apache POI 的相关依赖库。