首页 > 解决方案 > 减去单元格值

问题描述

所以,我在工作簿中有两列 - 材料名称和数量。所以我需要通过用户输入找到素材,然后得到用户想要销售的素材数量并进行减法。例如我们有行:

tissue   15

我们接受用户的输入:

Material that should be soled:
tissue
How many:
12

然后程序需要在这一行中找到组织和数量并减去它,然后更新 xls 文件中的信息,如:

tissue  3 

在这里我尝试了代码,它找到用户的输入材料,但不减去它

public void Order() {
        System.out.println("Material that should be soled: ");
        java.util.Scanner in = new java.util.Scanner(System.in);
        String toFind = in.nextLine();
        System.out.println("How many?: ");
        int quantity = in.nextInt();
    int searchColumn = 1;
        try (Workbook workbook = WorkbookFactory.create(new FileInputStream("solty.xls"));
             FileOutputStream fileout = new FileOutputStream("solty.xls")) {

            DataFormatter formatter = new DataFormatter();

            Sheet sheet = workbook.getSheetAt(0);
           
            for (int r = sheet.getLastRowNum(); r >= 0; r--) {
                Row row = sheet.getRow(r);
                if (row != null) {
                    for (int c = 0; c < row.getLastCellNum(); c++) {
                        Cell cell = row.getCell(c);
                        String value = formatter.formatCellValue(cell);
                        if (toFind.equals(value)) {
                            System.out.println("Text " + toFind + " found at " + cell.getAddress());
                            Cell cellInSearchColumn = row.getCell(searchColumn);
                            cellInSearchColumn.setCellValue(cellInSearchColumn.getNumericCellValue()-quantity);
                        }
                    }
                }
                workbook.write(fileout);


            }
        } catch (InvalidFormatException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

标签: javaexcelapache-poi

解决方案


推荐阅读