使用Apache POI设置单元格样式时,可以通过CellStyle对象设置单元格的样式,包括颜色和对齐方式。
下面是一个示例代码,演示如何使用Apache POI设置单元格样式,将单元格的背景颜色设置为黄色,并将文本向右对齐。
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileOutputStream;
import java.io.IOException;
public class CellStyleExample {
public static void main(String[] args) throws IOException {
// 创建工作簿和工作表
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Sheet1");
// 创建单元格样式
CellStyle style = workbook.createCellStyle();
// 设置背景颜色为黄色
style.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
// 设置文本对齐方式为右对齐
style.setAlignment(HorizontalAlignment.RIGHT);
// 创建单元格并设置样式
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("Hello, Apache POI!");
cell.setCellStyle(style);
// 保存工作簿到文件
try (FileOutputStream outputStream = new FileOutputStream("output.xlsx")) {
workbook.write(outputStream);
}
System.out.println("Excel文件生成完成。");
}
}
这段代码创建一个新的Excel文件,将单元格A1设置为黄色背景,并将文本向右对齐。最后,将工作簿保存到名为output.xlsx
的文件中。