使用Java从e​​xcel电子表格中获取字体大小

时间:2021-04-22 03:55:15

标签: java excel apache-poi xssf

我正在尝试获取 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) {

    }

1 个答案:

答案 0 :(得分:1)

您需要从单元格中获取字体。字体是单元格样式的一部分。单元格样式可以通过 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。这要复杂得多,需要对 HSSFXSSF 进行不同的处理。

相关问题