要使用Apache POI的XSSFWorkbook类来设置单元格的样式,你需要使用CellStyle类来创建和设置样式。以下是一个示例代码来解决你的编译错误:
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
public class ExcelExample {
public static void main(String[] args) {
// 创建工作簿和工作表
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("Sheet1");
// 创建样式
CellStyle cellStyle = workbook.createCellStyle();
// 设置样式属性
cellStyle.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
cellStyle.setAlignment(HorizontalAlignment.CENTER);
// 创建单元格并应用样式
XSSFCell cell = sheet.createRow(0).createCell(0);
cell.setCellValue("Hello World");
cell.setCellStyle(cellStyle);
// 保存工作簿
try {
workbook.write(new FileOutputStream("example.xlsx"));
workbook.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
在这个示例中,我们创建一个XSSFWorkbook对象代表一个Excel工作簿,然后使用createCellStyle()方法创建一个新的CellStyle对象。我们可以使用CellStyle的各种方法来设置样式属性,如填充颜色、填充模式和对齐方式。然后,我们创建一个XSSFCell对象来表示一个单元格,并使用setCellStyle()方法将样式应用于该单元格。
最后,我们将工作簿保存到一个文件中。请确保你已经在你的项目中包含了Apache POI的相关依赖。