XSSFWorkbook 创建多种样式后!获取指定样式
时间: 2023-06-18 22:04:25 浏览: 90
在创建多种样式之后,可以通过 `XSSFCellStyle` 的 `equals()` 方法比较两个样式是否相同,如果相同则获取该样式。示例代码如下:
```java
// 创建工作簿和工作表
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("Sheet1");
// 创建样式1
XSSFCellStyle style1 = workbook.createCellStyle();
style1.setFillForegroundColor(IndexedColors.RED.getIndex());
style1.setFillPattern(FillPatternType.SOLID_FOREGROUND);
// 创建样式2
XSSFCellStyle style2 = workbook.createCellStyle();
style2.setFillForegroundColor(IndexedColors.BLUE.getIndex());
style2.setFillPattern(FillPatternType.SOLID_FOREGROUND);
// 创建样式3
XSSFCellStyle style3 = workbook.createCellStyle();
style3.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
style3.setFillPattern(FillPatternType.SOLID_FOREGROUND);
// 获取样式1
XSSFCellStyle targetStyle = null;
for (int i = 0; i < sheet.getNumMergedRegions(); i++) {
CellRangeAddress range = sheet.getMergedRegion(i);
int firstRow = range.getFirstRow();
int lastRow = range.getLastRow();
int firstCol = range.getFirstColumn();
int lastCol = range.getLastColumn();
for (int j = firstRow; j <= lastRow; j++) {
for (int k = firstCol; k <= lastCol; k++) {
XSSFCellStyle cellStyle = (XSSFCellStyle) sheet.getRow(j).getCell(k).getCellStyle();
if (cellStyle.equals(style1)) {
targetStyle = cellStyle;
break;
}
}
if (targetStyle != null) {
break;
}
}
if (targetStyle != null) {
break;
}
}
if (targetStyle != null) {
// 获取到目标样式后可以进行操作
// 例如:设置字体
XSSFFont font = workbook.createFont();
font.setFontName("Arial");
font.setFontHeightInPoints((short) 12);
targetStyle.setFont(font);
}
```
阅读全文