如何使用XSSFCellStyle类设置单元格的格式
要使用XSSFCellStyle类设置单元格的格式,需要使用Apache POI库。下面是使用Apache POI的maven依赖:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
下面是一个示例的Excel样例:
| 姓名 | 年龄 | 职业 |
| ------- | ---- | -------- |
| John | 25 | Engineer |
| Alice | 30 | Doctor |
| Michael | 35 | Lawyer |
下面是一个使用XSSFCellStyle类设置单元格格式的Java示例代码:
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
public class CellStyleExample {
public static void main(String[] args) throws Exception {
// 创建工作簿和工作表
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Sheet1");
// 创建单元格样式
CellStyle style = workbook.createCellStyle();
style.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
// 创建字体样式
Font font = workbook.createFont();
font.setBold(true);
style.setFont(font);
// 创建行和单元格,并设置样式
Row row1 = sheet.createRow(0);
Cell cell1 = row1.createCell(0);
cell1.setCellValue("姓名");
cell1.setCellStyle(style);
Cell cell2 = row1.createCell(1);
cell2.setCellValue("年龄");
cell2.setCellStyle(style);
Cell cell3 = row1.createCell(2);
cell3.setCellValue("职业");
cell3.setCellStyle(style);
// 写入文件
try (FileOutputStream outputStream = new FileOutputStream("example.xlsx")) {
workbook.write(outputStream);
}
System.out.println("Excel文件生成成功!");
}
}
在这个示例代码中,我们创建了一个新的工作簿和工作表,然后创建了一个单元格样式和字体样式,并将它们应用到单元格中。最后,我们将工作簿写入到文件中。生成的Excel文件将会在工作簿的第一行应用黄色背景和加粗字体的样式。