问题描述:使用Apache POI尝试导出和着色Excel行时,可能会遇到以下异常:
java.lang.IllegalArgumentException: Invalid CellStyle specified for cell
解决步骤:
CellStyle style = workbook.createCellStyle(); style.setFillPattern(FillPatternType.SOLID_FOREGROUND); //设置填充模式 style.setFillForegroundColor(IndexedColors.YELLOW.getIndex()); //设置填充颜色
Row row = sheet.getRow(0); //获取第一行 Cell cell = row.getCell(0); //获取第一个单元格 cell.setCellStyle(style); //设置CellStyle对象
完整示例代码:
import java.io.FileOutputStream; import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelExportExample {
public static void main(String[] args) {
try {
// 创建工作表和行列
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet();
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
// 设置样式
CellStyle style = workbook.createCellStyle();
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
style.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
cell.setCellStyle(style);
// 输出文件
FileOutputStream output = new FileOutputStream("example.xlsx");
workbook.write(output);
output.close();
workbook.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}