java - 从 Excel 文件读取数字 - Java - Swing

标签 java swing apache-poi

我创建了一个可以上传并从 Excel 文件中获取一些数字的工具

public static void main( String[] args ) throws Exception {
    JFileChooser fc = new JFileChooser();
    int returnVal = fc.showOpenDialog(null);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        App.file = fc.getSelectedFile();
        //This is where a real application would open the file.
        System.out.println("Opening: " + App.file.getName() + ".");
    } else {
        System.out.println("Open command cancelled by user.");
    }       


    workbook = Workbook.getWorkbook(App.file);
      Sheet sheet = workbook.getSheet(1);

      Cell cell1 = sheet.getCell(4, 27);
      System.out.println(cell1.getContents());
      Cell cell2 = sheet.getCell(4, 28);
          System.out.println(cell11.getContents());




      App.eStop = false;
     int i = 0 ;
    while (App.eStop == false) {
         try {


          cell3 = sheet.getCell(9, i);
          System.out.println(cell3.getContents());  
         } catch (Exception e) {
             App.eStop = true; 
         };
        i++;


    }


    System.out.println("done");

我使用以下命令将此值粘贴到其他工具

psess.GetPS().SendKeys(cell1.getContents(), 8, 18);

Excel 文件中的所有值都是数字。 有时我会得到小数(例如 2.02)。

因为我无法更改 Excel 文件,所以可以告诉我的应用程序忽略 .02 并仅保留 2 吗?

最佳答案

如果 Excel 文件为您尝试读取的单元格设置了正确的格式,您可以尝试应用该格式,从而获取与 Excel 显示格式相同的值。

参见例如以下示例来自 http://poi.apache.org/spreadsheet/eval.html 的文档

FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();

// suppose your formula is in B3
CellReference cellReference = new CellReference("B3"); 
Row row = sheet.getRow(cellReference.getRow());
Cell cell = row.getCell(cellReference.getCol()); 

CellValue cellValue = evaluator.evaluate(cell);

switch (cellValue.getCellType()) {
    case Cell.CELL_TYPE_BOOLEAN:
        System.out.println(cellValue.getBooleanValue());
        break;
    case Cell.CELL_TYPE_NUMERIC:
        System.out.println(cellValue.getNumberValue());
        break;
    case Cell.CELL_TYPE_STRING:
        System.out.println(cellValue.getStringValue());
        break;
    case Cell.CELL_TYPE_BLANK:
        break;
    case Cell.CELL_TYPE_ERROR:
        break;

    // CELL_TYPE_FORMULA will never happen
    case Cell.CELL_TYPE_FORMULA: 
        break;
}

关于java - 从 Excel 文件读取数字 - Java - Swing,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35295312/

相关文章:

java - Jsp Struts2中Action类的调用函数

java - 将二进制转换为文本时遇到问题

java - 获取 Math.abs 的十进制数输入/输出

java - 在JTable中设置不同颜色的行?

java - JAVA中按钮VS图像按钮

java - 使用 Apache POI API 从 Excel 文件读取值

java - 使用 autoSizeColumn 时列在 XSSF Apache POI 中隐藏

java - 如何将excel数据读入 vector 表

java - 如何在 IntelliJ Java IDEA 调试器中设置 LocalDate

java - 使用助记符调用JButton按下动画