我想读取一个xlsx文件,其内容是复数。我使用apache poi。但我不知道如何使用这个库从 Excel 读取复数。
最佳答案
复数以字符串形式存储在 Excel
单元格中。
例如,=COMPLEX(3,4)
的结果值将是字符串 3+4i
。这也可以通过 apache poi 读取,方式与其他字符串单元格值相同。
更好的方法是将 DataFormatter
与 FormulaEvaluator
结合使用。
示例:
Excel:
Java:
import org.apache.poi.ss.usermodel.*;
import java.io.FileInputStream;
class ExcelReadCOMPLEX {
public static void main(String[] args) throws Exception {
DataFormatter formatter = new DataFormatter();
Workbook workbook = WorkbookFactory.create(new FileInputStream("COMPLEX.xlsx"));
FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
Sheet sheet = workbook.getSheetAt(0);
Row row = sheet.getRow(1);
Cell cell;
for (int c = 0 ; c < 3; c++) {
cell = row.getCell(c);
System.out.println(cell.getCellFormula()); //COMPLEX(3,4), IMREAL(A2), IMAGINARY(A2)
System.out.println(formatter.formatCellValue(cell, evaluator)); //3+4i, 3, 4
}
String[] formulas = new String[]{"COMPLEX(5, -6)", "IMREAL(INDEX(A:A, ROW()))", "IMAGINARY(INDEX(A:A, ROW()))"};
row = sheet.createRow(2);
for (int c = 0 ; c < 3; c++) {
cell = row.createCell(c);
cell.setCellFormula(formulas[c]);
System.out.println(cell.getCellFormula());
System.out.println(formatter.formatCellValue(cell, evaluator)); //5-6i, 5, -6
}
workbook.close();
}
}
结果打印到stdout
:
COMPLEX(3,4)
3+4i
IMREAL(A2)
3
IMAGINARY(A2)
4
COMPLEX(5, -6)
5-6i
IMREAL(INDEX(A:A, ROW()))
5
IMAGINARY(INDEX(A:A, ROW()))
-6
问题是然后呢?您想在 Java
中用它做什么?
关于java - 如何使用 Apache Poi 从 excel 读取复数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50433698/