就目前而言,Apache POI 不允许对生成的 excel 文件中的数据进行简单的排序。
您当然可以使用 Aspose,但这需要许可证。我要由 Apache POI 处理并用于结束 excel 文档的传入数据是 XML 格式:
<transaction>
<transactionDate>2015-10-23T00:00:00+03:00</transactionDate>
<transactionAmount>23</transactionAmount>
<transactionBatch>000</transactionBatch>
<transactionBatchDate>2015-10-27T10:12:00+02:00</transactionBatchDate>
<transactionServiceFee>1</transactionServiceFee>
<transactionNetAmount>22</transactionNetAmount>
</transaction>
<transaction>
<transactionDate>2016-02-25T11:13:59+02:00</transactionDate>
<transactionAmount>-1000</transactionAmount>
<transactionBatch>000</transactionBatch>
<transactionBatchDate>2016-02-25T11:14:40+02:00</transactionBatchDate>
<transactionServiceFee>-30</transactionServiceFee>
<transactionNetAmount>-970</transactionNetAmount>
</transaction>
<transaction>
<transactionDate>2015-10-23T00:00:00+03:00</transactionDate>
<transactionAmount>23</transactionAmount>
<transactionBatch>001</transactionBatch>
<transactionBatchDate>2015-10-27T10:12:00+02:00</transactionBatchDate>
<transactionServiceFee>1</transactionServiceFee>
<transactionNetAmount>22</transactionNetAmount>
</transaction>
<transaction>
<transactionDate>2016-02-25T11:13:59+02:00</transactionDate>
<transactionAmount>-1000</transactionAmount>
<transactionBatch>001</transactionBatch>
<transactionBatchDate>2016-02-25T11:14:40+02:00</transactionBatchDate>
<transactionServiceFee>-30</transactionServiceFee>
<transactionNetAmount>-970</transactionNetAmount>
</transaction>
....
我必须在结果 Excel 中以以下方式呈现数据:
1. transactionBatch 000: transactionBatchDate (sorted by date in asc.)
1.1. transaction: transactionDate (sorted by date grouped by above batch)
1.2. transaction: transactionDate (sorted by date grouped by above batch)
1.3. transaction: transactionDate (sorted by date grouped by above batch)
2. transactionBatch 001: transactionBatchDate (sorted by date in asc.)
2.1. transaction: transactionDate (sorted by date grouped by above batch)
2.2. transaction: transactionDate (sorted by date grouped by above batch)
2.3. transaction: transactionDate (sorted by date grouped by above batch)
为了解决我的问题,我首先必须按日期对 XML 中的数据进行排序。这是通过让我的模型实现 Comparable 接口来实现的。
在我可以像这样按日期批次排序之后:
Map<String, String> transactionBatchHashMap = new HashMap<>();
for (int i = 0; i < nodeList.getLength(); i++) {
transactionBatchHashMap.put(getNodeValue(nodeList, i, "transactionBatch"),
getNodeValue(nodeList, i, "transactionBatchDate"));
}
transactionBatchHashMap = sortMapByValues(transactionBatchHashMap);
然后通过使用简单的 foreach 循环,我可以将事务分组到每个批次下:
for (Map.Entry<String, String> entry : transactionBatchHashMap.entrySet()) {
HSSFRow batchRow = spreadSheet.createRow(rowNumber);
...
for (int i = 0; i < nodeList.getLength(); i++) {
String transactionBatchValue = getNodeValue(nodeList, i, "transactionBatch");
String hashMapBatchKeyValue = entry.getKey();
if (transactionBatchValue.equals(hashMapBatchKeyValue)) {
...