I'm reading from excel in the format of XLSX, and storing the data for each sheet in a list of maps. Each item in the list represents the columns and the values for each row in the sheet. However, the order of columns and values for each map, is not in the right order of the original excel sheet. What I want it the order from left to right, so I could later write to excel using my list of maps. What can I do to make it happen? An example of the excel sheet:
column 1 column2
value1 value2
value3 value4
The list of maps with the order mixed up:
0 = "column2" -> value2
"column1" -> value1
1 = "column2" -> value4
"column1" -> value3
snippet of my code:
public static List<Map<String, String>> readExcelSheet(Sheet sheet) {
Iterator<Row> rows = sheet.iterator();
if (!rows.hasNext()) {
return Collections.emptyList();
}
Row header = rows.next();
List<String> keys = new ArrayList<>();
for (Cell cell : header) {
String value = cell.getStringCellValue();
if (!value.isEmpty()) {
keys.add(value);
} else {
break;
}
}
List<Map<String, String>> result = new ArrayList<>();
while (rows.hasNext()) {
Row row = rows.next();
Map<String, String> rowMap = new HashMap<>();
for (int i = 0; i < keys.size(); i) {
Cell cell = row.getCell(i, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
String value;
value = cell.toString();
rowMap.put(keys.get(i), value);
}
// Only add rows which aren't empty
if (!rowMap.values().stream().allMatch(String::isEmpty)) {
result.add(rowMap);
}
}
return result;
}
CodePudding user response:
Quite not sure about the output that you want, and what do you mean order mixed up
. Is this your expected output?
0 = "column1" -> value1
"column2" -> value2
1 = "column1" -> value3
"column2" -> value4
If so, you can try to use LinkedHashMap or TreeMap to order your map.
For more reading here another link