java - Apache POI生成文档并在内部排序

标签 java excel apache-poi

我正在尝试通过“transactionBatch”参数对我的交易进行“分组”。我看到我的 HashMap 成功收集了唯一的批处理。当我调试下面的代码时,一切似乎都正确完成。虽然当我检查Excel文件时,交易并没有相应地分组。它们应该分组:

batch # 1:
- transaction with batch # 1
- transaction with batch # 1

batch # 2:
- transaction with batch # 2
- transaction with batch # 2

结果 Excel 文件包含:

batch # 1:
- transaction with batch # 1
- transaction with batch # 2

batch # 2:
- transaction with batch # 4
- transaction with batch # 1  

这是代码:

HashMap<String, String> hashMap = new HashMap<>();

        for (int i = 0; i < nodeList.getLength(); i++) {
            hashMap.put(((Element) (nodeList.item(i))).getElementsByTagName("transactionBatch").item(0)
                    .getFirstChild().getNodeValue(), ((Element) (nodeList.item(i))).getElementsByTagName("transactionBatchDate").item(0)
                    .getFirstChild().getNodeValue());
        }

        for (Map.Entry<String, String> entry : hashMap.entrySet()) {
            for (int i = 0; i < nodeList.getLength(); i++) {
                String transactionBatch = ((Element) (nodeList.item(i))).getElementsByTagName("transactionBatch").item(0)
                        .getFirstChild().getNodeValue();
                String key = entry.getKey();
                if (transactionBatch.equals(key)) {
                    HSSFRow dynamicRow = spreadSheet.createRow(i + 2);

                    if (nodeList.getLength() != 0) {
                        cell = dynamicRow.createCell((short) 0);
                        cell.setCellValue(((Element) (nodeList.item(i))).getElementsByTagName("transactionNumber").item(0)
                                .getFirstChild().getNodeValue());
                        cell.setCellStyle(styleWithDataCentered);

                        ...

                        cell = dynamicRow.createCell((short) 8);
                        cell.setCellValue(((Element) (nodeList.item(i))).getElementsByTagName("transactionBatch").item(0)
                                .getFirstChild().getNodeValue());
                        cell.setCellStyle(styleWithDataCentered);
                    }
                }
            }
        }

最佳答案

问题出在这一行:

HSSFRow dynamicRow = spreadSheet.createRow(i + 2);

我必须在 for 方法之外分配另一个变量来保留 int:

int rowNumber = 2;

然后每行增加它的值。

HSSFRow dynamicRow = spreadSheet.createRow(rowNumber += 1);

关于java - Apache POI生成文档并在内部排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39977110/

相关文章:

java - jgraphx 上划线顶点标签

regex - 从 Excel 工作表上的字符串中删除 unicode 字符

excel - 如何计算Excel中不同值的重复次数?

java - 检查方法链中的最后一个 getter 是否不为空

java - Android volley future 请求超时

java - 无法设置填充颜色 Apache POI Excel 工作簿

java - 由于使用 apache-poi 库创建下拉列表而导致 Excel 损坏

java - POI 3.2 图像高度/宽度控制

java - 在 Android 上使用 JNI 的成本

excel - 将列字母转换为数字