如何解决使用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
或通过 int
获得 CelStyle.getFontIndexAsInt
或通过 int
依赖项获得 CelStyle.getFontIndex
使用的 apache poi
版本。后者使用当前的 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
。这要复杂得多,需要对 HSSF
和 XSSF
进行不同的处理。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。