使用 Java 从 Excel 电子表格中获取字体大小



我正在尝试在 excel 电子表格上获取标题的字体大小,但我无法获得它。我尝试使用以下方法来获取尺寸,但一直无法获得尺寸。以下都对我不起作用,因为它没有返回正确的字体大小。 headerFont.getFontHeight (); headerFont.getFontHeightInPoints (); 有什么建议吗?

以下是我拥有的代码:

try {
FileInputStream file = new FileInputStream(new File(fileName));
XSSFWorkbook workbook = new XSSFWorkbook(file);
XSSFSheet sheet = workbook.getSheetAt(1);
int numRows = sheet.getLastRowNum() + 1;
int numCols = sheet.getRow(0).getLastCellNum();
Iterator<Row> rowIterator = sheet.iterator();
for (int i = 0; i < 1; i++) {
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
for (int j = 0; j < numCols; j++) {
Cell cell = cellIterator.next();
Font headerFont = workbook.createFont();
headerFontFamily = headerFont.getFontName();
headerFont.getFontHeight();
headerFont.getFontHeightInPoints();
}
}
file.close();
} catch (Exception e) {
}

您需要从单元格中获取字体。字体是单元格样式的一部分。单元格样式可以通过Cell.getCellStyle获得。然后,可以使用的字体的索引作为short通过CelStyle.getFontIndex或通过CelStyle.getFontIndexAsIntint,或者通过所用版本的apache poi依赖CelStyle.getFontIndexint。后者使用当前5.0.0版本工作。

完整示例:

import org.apache.poi.ss.usermodel.*;
import java.io.FileInputStream;
class ReadExcel {
public static void main(String[] args) throws Exception {
Workbook workbook = WorkbookFactory.create(new FileInputStream("./ExcelExample.xlsx"));
FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();  

DataFormatter dataFormatter = new DataFormatter();

Sheet sheet = workbook.getSheetAt(0);
for (Row row : sheet) {
for (Cell cell : row) {
String value = dataFormatter.formatCellValue(cell, evaluator);
System.out.println(value);
CellStyle style = cell.getCellStyle();
//short fontIdx = style.getFontIndex(); // depends on apache poi version
//int fontIdx = style.getFontIndexAsInt(); // depends on apache poi version
int fontIdx = style.getFontIndex(); // depends on apache poi version
Font font = workbook.getFontAt(fontIdx);
System.out.println(font.getFontName() + ", " + font.getFontHeightInPoints());
}
}
workbook.close();
}
}

备注:仅当单元格只有一种字体时,此操作才有效。如果单元格包含富文本字符串,则每个格式文本运行都有字体。然后需要获取和遍历RichTextString。这要复杂得多,需要为HSSFXSSF做不同的操作。

最新更新