如何使用Apache Poi读取Excel中的复数?
用Apache POI读取Excel中的复数
嘿,刚好我之前处理过类似的需求,给你一步步讲清楚怎么用Apache POI搞定Excel里的复数读取:
首先得明确:只有XLSX格式(.xlsx)的文件支持原生复数类型,老的XLS格式(.xls)本身就没有复数的存储规范,所以HSSF库是处理不了的,得用XSSF来操作。
一、读取Excel原生存储的复数
Excel里直接输入的复数(比如通过Excel的复数格式设置,或者公式生成的复数结果),在Apache POI中是用XSSFComplexNumber类来表示的。你可以通过XSSFCell的getComplexNumber()方法来获取,示例代码如下:
import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFComplexNumber; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.FileInputStream; import java.io.IOException; public class ReadComplexNumbers { public static void main(String[] args) throws IOException { try (FileInputStream fis = new FileInputStream("your-complex-file.xlsx"); XSSFWorkbook workbook = new XSSFWorkbook(fis)) { Sheet sheet = workbook.getSheetAt(0); for (Row row : sheet) { for (Cell cell : row) { if (cell instanceof XSSFCell) { XSSFCell xssfCell = (XSSFCell) cell; XSSFComplexNumber complexNum = xssfCell.getComplexNumber(); if (complexNum != null) { // 获取实部和虚部 double realPart = complexNum.getReal(); double imaginaryPart = complexNum.getImaginary(); System.out.printf("复数:%.2f + %.2fi%n", realPart, imaginaryPart); } else { // 不是复数,按常规类型处理 handleNonComplexCell(xssfCell); } } } } } } private static void handleNonComplexCell(XSSFCell cell) { switch (cell.getCellType()) { case STRING: System.out.println("字符串:" + cell.getStringCellValue()); break; case NUMERIC: if (DateUtil.isCellDateFormatted(cell)) { System.out.println("日期:" + cell.getDateCellValue()); } else { System.out.println("普通数字:" + cell.getNumericCellValue()); } break; case BOOLEAN: System.out.println("布尔值:" + cell.getBooleanCellValue()); break; default: System.out.println("其他类型单元格"); } } }
二、处理字符串形式的复数
如果你的Excel里的复数是用户手动输入的字符串(比如直接敲入3+4i或者5-2.5i),这时候POI不会识别为原生复数,需要你手动解析字符串。可以用正则表达式来提取实部和虚部:
import java.util.regex.Matcher; import java.util.regex.Pattern; // 在handleNonComplexCell方法里添加字符串解析逻辑 if (cell.getCellType() == CellType.STRING) { String cellText = cell.getStringCellValue().trim(); // 匹配常见的复数格式:a+bi、a-bi、-a+bi等 Pattern complexPattern = Pattern.compile("([-+]?\\d+(\\.\\d+)?)\\s*([+-])\\s*(\\d+(\\.\\d+)?)i"); Matcher matcher = complexPattern.matcher(cellText); if (matcher.matches()) { double real = Double.parseDouble(matcher.group(1)); // 把符号和虚部数字拼接起来 double imaginary = Double.parseDouble(matcher.group(3) + matcher.group(4)); System.out.printf("解析出的复数:%.2f + %.2fi%n", real, imaginary); } else { System.out.println("普通字符串:" + cellText); } }
三、注意事项
- 确保你使用的Apache POI版本足够新(建议3.17及以上),旧版本可能没有
XSSFComplexNumber相关的API - 如果是公式生成的复数,需要确保公式已经计算完成。如果文件里的公式结果是未计算的,可以用
FormulaEvaluator来触发计算:FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator(); CellValue cellValue = evaluator.evaluate(xssfCell); // 如果计算结果是复数,同样可以通过XSSF相关方法获取
内容的提问来源于stack exchange,提问作者zahra.bsh
相关产品推荐
相关产品推荐

