使用Java更新包含公式的Excel文件

时间:2016-05-29 06:28:36

标签: java excel

我已经创建了一个excel文件,如下所示:我想更新它,如下所示:

1-检查行是否为零值(如果是,则将每行的u1求和为0,如果不是则检查下一行)。

2-求出求和后零值的每一行的平均值。

3-用平均值替换零值单元格。

4-将更新的excel复制到其他excel。

请问有人帮忙吗?

    XSSFWorkbook workbook = new XSSFWorkbook();
    XSSFSheet sheet = workbook.createSheet("correct missing Value");
    Map<String, Object[]> data = new TreeMap<String, Object[]>();

    data.put("1", new Object[]{"ID", "USERS", I1","I2","I3","I4","I5","I6"});
    data.put("2", new Object[]{1, "U1", 4, 2, 3, 5, 3, 4});
    data.put("3", new Object[]{2, "U2", 3, 0, 2, 4, 2, 3});
    data.put("4", new Object[]{3, "U3", 5, 0, 4, 4, 4, 5});
    data.put("5", new Object[]{4, "U4", 0, 1, 2, 4, 2, 3});

    Set<String> keyset = data.keySet();
    int rownum = 0;
    for (String key : keyset) {
        Row row = sheet.createRow(rownum++);
        Object[] objArr = data.get(key);
        int cellnum = 0;
        for (Object obj : objArr) {
            Cell cell = row.createCell(cellnum++);
            if (obj instanceof String)
                cell.setCellValue((String) obj);
            else if (obj instanceof Integer)
                cell.setCellValue((Integer) obj);
        }
    }
    try {

        FileOutputStream out = new FileOutputStream(new File("Test.xlsx"));
        workbook.write(out);
        out.close();
        System.out.println("Test.xlsx written successfully on disk.");
    } catch (Exception e) {
        e.printStackTrace();
    }
    }

1 个答案:

答案 0 :(得分:0)

你刚刚在这行 I1 之前忘记了

data.put("1", new Object[]{"ID", "USERS", I1","I2","I3","I4","I5","I6"});

正确的行是:

data.put("1", new Object[]{"ID", "USERS", "I1","I2","I3","I4","I5","I6"});

这有效