简体   繁体   中英

Apache POI excel print subtotals in a particular order

I have an Asset POJO:

public class Asset implements Serializable {
    //serialVersionUID 
    private String quarter;
    private String assetType;
    private BigDecimal assetAttributes;
// more assetAttributes like price, etc, getters and setters
}

and then I have this method that takes a list of this POJO and a Apache POI Sheet, and writes the list content to the sheet:

public void addContent (List<Asset> listOfAsset, Sheet sheet) {
    //make a row counter and a cell counter
    SortedSet<String> quarters = new TreeSet<String>();
    for (Asset asset : listOfAsset) {
      quarters.add(asset.getQuarter());
      //write content to sheet
      row.createCell().setCellValue();
    }
    addSubtotals();
}

then I have addSubtotals method that takes necessary information and do a SUMIF formula:

private void addSubtotals (//params) {
    for (String s : quarters) {
      Row row = sheet.createRow(rowCounter++);
      row.createCell(0).setCellValue(// quarter);
      for (int i = 2; i < cellCounter; i++) {
        row.createCell(i).setCellFormula(
        "SUMIF(// if the printed quarter equals the one in the quarters set, 
            then add all the attributes for all asset types)");
      }
   }
}

and that's all working fine, except the subtotals are all at the bottoms of the list. How do I do the subtotal after each quarter? I don't know ahead of time how many quarters there will be, or how many asset types there will be in each quarter.

I thought about putting the subtotal method in the for loop that adds content, but I can't do a SUMIF because the number of quarters and asset types are unknown. I could possibly do a TreeMap but I'm not sure about the details.

You might need to categorize your asset pojo's ahead of time. You'll need to create a Map (String, Map(String, Asset)) which represents a map of quarter to map of asset type to asset. Then you can use a 3-nested loop to loop over each quarter then over each asset type within that quarter then over each asset. Use treemap implementation if order is important. Doing it this way will give u the ability to do something special when u reach the end of an asset type or quarter, and u can even keep track of your totals using local variables in the loops themselves.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM