Apache-poi:想遍历一个excel列并总结下一列中的相应值

时间:2019-01-13 19:22:30

标签: java excel apache-poi

我在excel中的数据如下:

Orgs    Bill
Org1    1.0
Org2    2.0
Org3    3.0
Org3    8.0
Org2    10.0
Org1    12.0

我想要的结果是汇总对应于类似组织的值: 单位1:13.0 组织2:12.0 Org3:11.0

我可以使用以下代码来实现。只想知道是否有更好的方法。

    List<String> duplicateOrgs = new ArrayList<String>();
    LinkedHashSet<String> orgs;
    LinkedHashMap<String, Float> orgsAndSum = new LinkedHashMap<String, Float>(); 

    File file = new File("C:\\Users\\Himanshu Chand\\Desktop\\OrgData\\OrgDataLarge.xls");
    FileInputStream inputStream = new FileInputStream(file);
    Workbook workbook = null;
    workbook = new HSSFWorkbook(inputStream);

    Sheet sheet = workbook.getSheet("Sheet1");

    int rowCount = sheet.getLastRowNum()-sheet.getFirstRowNum();

    for (int i = 1; i < rowCount+1; i++)
    {
        Row row = sheet.getRow(i);
        duplicateOrgs.add(row.getCell(0).getStringCellValue());   //here i am looping through the first column and storing all the orgs in a list.
    } 

    orgs= new LinkedHashSet<String>(duplicateOrgs); //storing the list into set to get unique orgs.

    Iterator value = orgs.iterator(); 

    while (value.hasNext()) 
    { 
        String org=(String) value.next();
        float sum=0;
        for (int i = 1; i < rowCount+1; i++)
        {
            Row row = sheet.getRow(i);
            if(org.equals(row.getCell(0).getStringCellValue()))
            {
                sum=(float) (sum+row.getCell(1).getNumericCellValue()); //now comparing the set of orgs with the first column and summing the bill wherever there is a match.
            }
        } 
        orgsAndSum.put(org, sum);
    } 

   for (Entry<String, Float> entry : orgsAndSum.entrySet())
   {
       System.out.println(entry.getKey() + "/" + entry.getValue());
   }

}  

1 个答案:

答案 0 :(得分:1)

您可以直接在Excel电子表格中或与org.apache.poi.ss.formula.functions.Countif类一起使用COUNTIF函数,而不用手工进行操作。看看 Formula Examples,了解POI如何处理内置的Excel函数。