在Java中获取Excel中的数据时,如果遇到公式,可以通过使用Apache POI或JExcel等库来解析公式并获取计算结果。

对于公式中的字符,可以使用公式求值的方法将其转换为相应的数字。以下是使用Apache POI库的示例代码:

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileInputStream;
import java.io.IOException;

public class ExcelReader {
    public static void main(String[] args) {
        try {
            FileInputStream file = new FileInputStream("path/to/excel/file.xlsx");
            Workbook workbook = new XSSFWorkbook(file);
            Sheet sheet = workbook.getSheetAt(0);

            // 遍历每一行
            for (Row row : sheet) {
                // 遍历每一列
                for (Cell cell : row) {
                    if (cell.getCellType() == CellType.FORMULA) {
                        // 获取公式计算结果
                        FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
                        CellValue cellValue = evaluator.evaluate(cell);
                        
                        if (cellValue.getCellType() == CellType.NUMERIC) {
                            // 公式计算结果为数字
                            double value = cellValue.getNumberValue();
                            System.out.println(value);
                        } else if (cellValue.getCellType() == CellType.STRING) {
                            // 公式计算结果为字符
                            String value = cellValue.getStringValue();
                            System.out.println(value);
                        }
                    } else if (cell.getCellType() == CellType.NUMERIC) {
                        // 单元格为数字
                        double value = cell.getNumericCellValue();
                        System.out.println(value);
                    } else if (cell.getCellType() == CellType.STRING) {
                        // 单元格为字符
                        String value = cell.getStringCellValue();
                        System.out.println(value);
                    }
                }
            }

            workbook.close();
            file.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

上述代码通过遍历Excel的每一行和每一列,判断单元格的类型,如果是公式类型,则使用公式求值器将公式转换为计算结果。如果公式计算结果为数字,则获取其数值;如果为字符,则获取其字符串值。对于非公式单元格,直接获取其数值或字符串值

java中获取到excel中的数据不是数据是公式怎么办公式里面的不是数字是字符怎么办

原文地址: https://www.cveoy.top/t/topic/iQBE 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录