69 lines
2.0 KiB
Java
69 lines
2.0 KiB
Java
package de.arminwolf.financeanalyzer.util;
|
|
|
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
|
import org.apache.poi.openxml4j.util.ZipSecureFile;
|
|
import org.apache.poi.ss.usermodel.Cell;
|
|
import org.apache.poi.ss.usermodel.Row;
|
|
import org.apache.poi.ss.usermodel.Sheet;
|
|
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
|
|
|
import java.io.ByteArrayOutputStream;
|
|
import java.io.IOException;
|
|
import java.io.InputStream;
|
|
import java.util.ArrayList;
|
|
import java.util.HashMap;
|
|
import java.util.List;
|
|
import java.util.Locale;
|
|
import java.util.Map;
|
|
import java.util.Objects;
|
|
import java.util.Optional;
|
|
|
|
public class XlsxToJsonConverter {
|
|
|
|
|
|
public static final String JSON_EXTENSION = ".json";
|
|
|
|
|
|
public static List<Map<String, String>> readXlsx(InputStream inputFile) {
|
|
List<Map<String, String>> data = new ArrayList<>();
|
|
ZipSecureFile.setMinInflateRatio(0.001);
|
|
try (XSSFWorkbook workbook = new XSSFWorkbook(inputFile)) {
|
|
Sheet sheet = workbook.getSheetAt(0);
|
|
Row headerRow = sheet.getRow(0);
|
|
int lastColumnNum = headerRow.getLastCellNum();
|
|
for (int i = 1; i <= sheet.getLastRowNum(); i++) {
|
|
Row row = sheet.getRow(i);
|
|
Map<String, String> rowData = new HashMap<>();
|
|
for (int j = 0; j < lastColumnNum; j++) {
|
|
Cell cell = row.getCell(j);
|
|
String cellValue = "";
|
|
if (Objects.nonNull(cell)) {
|
|
cellValue = cell.toString();
|
|
}
|
|
rowData.put(convert2jsonKey(headerRow.getCell(j).toString()), cellValue);
|
|
}
|
|
data.add(rowData);
|
|
}
|
|
} catch (IOException e) {
|
|
e.printStackTrace();
|
|
}
|
|
return data;
|
|
}
|
|
|
|
|
|
private static String convert2jsonKey(final String string) {
|
|
return string.toLowerCase(Locale.GERMANY).replaceAll(" ", "-");
|
|
}
|
|
|
|
|
|
public static Optional<String> writeJson(List<Map<String, String>> data) {
|
|
try (ByteArrayOutputStream fos = new ByteArrayOutputStream()) {
|
|
ObjectMapper mapper = new ObjectMapper();
|
|
mapper.writerWithDefaultPrettyPrinter().writeValue(fos, data);
|
|
return Optional.of(fos.toString());
|
|
} catch (Exception e) {
|
|
return Optional.empty();
|
|
}
|
|
}
|
|
}
|