La clase para generar el mapa a partir de un excel enorme sería esta: ``` import java.io.InputStream; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.ListIterator; import java.util.LinkedList; import java.util.Map; import java.util.function.Function; import javax.xml.parsers.ParserConfigurationException; import org.xml.sax.ContentHandler; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import lombok.RequiredArgsConstructor; import lombok.Getter; import lombok.Setter; import lombok.NonNull; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.poi.openxml4j.exceptions.OpenXML4JException; import org.apache.poi.openxml4j.opc.OPCPackage; import org.apache.poi.openxml4j.opc.PackageAccess; import org.apache.poi.ss.util.CellAddress; import org.apache.poi.ss.util.CellReference; import org.apache.poi.ss.usermodel.DataFormatter; import org.apache.poi.util.XMLHelper; import org.apache.poi.xssf.eventusermodel.XSSFReader; import org.apache.poi.xssf.eventusermodel.ReadOnlySharedStringsTable; import org.apache.poi.xssf.eventusermodel.XSSFSheetXMLHandler; import org.apache.poi.xssf.eventusermodel.XSSFSheetXMLHandler.SheetContentsHandler; import org.apache.poi.xssf.model.Styles; import org.apache.poi.xssf.model.StylesTable; import org.apache.poi.xssf.model.SharedStrings; import org.apache.poi.xssf.usermodel.XSSFComment; @RequiredArgsConstructor @Getter @Setter public class ExcelToMap{ private static final Logger LOGGER = LogManager.getLogger(ExcelToMap.class); private class SheetToMap implements SheetContentsHandler { private boolean firstCellOfRow; private int currentRow = -1; private int currentCol = -1; private List key; private List value; public SheetToMap(){ currentRow = -1; currentCol = -1; firstCellOfRow = false; } @Override public void startRow(int rowNum){ firstCellOfRow = true; currentRow = rowNum; currentCol = -1; key = new LinkedList(); value = new LinkedList(); } @Override public void endRow(int rowNum){ if (rowNum == 0) return; map.merge(key, value, (value1, value2) -> { List mergedValue = new LinkedList(); ListIterator iterator1 = value1.listIterator(); ListIterator iterator2 = value2.listIterator(); while(iterator1.hasNext() && iterator2.hasNext()){ mergedValue.add(iterator1.next() + iterator2.next()); } return mergedValue; }); LOGGER.trace(String.format("Row %d parsed",rowNum)); } @Override public void cell(String cellReference, String formattedValue, XSSFComment comment){ if (currentRow == 0) return; if (firstCellOfRow) { firstCellOfRow = false; } if (cellReference == null) { cellReference = new CellAddress(currentRow, currentCol).formatAsString(); } if (formattedValue == null) { return; } currentCol = (new CellReference(cellReference)).getCol(); if(valuesIndexs.contains(currentCol)){ try{ value.add(parseValueFunction.apply(formattedValue)); LOGGER.trace(String.format("Cell %s parsed",cellReference)); } catch(Exception e){ value.add(0.0); LOGGER.warn(String.format("Value corresponding to %d collum from key %s is corrupted.", currentCol, key)); } } else if (keysIndexs.contains(currentCol)){ key.add(formattedValue); LOGGER.trace(String.format("Cell %s parsed",cellReference)); } else return; } } @NonNull private OPCPackage xlsxPackage; @NonNull private Map,List> map; @NonNull List keysIndexs; @NonNull List valuesIndexs; @NonNull Function parseValueFunction; /** * * @param styles The table of styles that may be referenced by cells in the sheet * @param strings The table of strings that may be referenced by cells in the sheet * @param sheetInputStream The stream to read the sheet-data from. * @throws java.io.IOException An IO exception from the parser, * possibly from a byte stream or character stream * supplied by the application. * @throws SAXException if parsing the XML data fails. */ public void processSheet(Styles styles, SharedStrings strings, SheetContentsHandler sheetHandler, InputStream sheetInputStream) throws IOException, SAXException { DataFormatter formatter = new DataFormatter(true); InputSource sheetSource = new InputSource(sheetInputStream); try { XMLReader sheetParser = XMLHelper.newXMLReader(); ContentHandler handler = new XSSFSheetXMLHandler(styles, null, strings, sheetHandler, formatter, false); sheetParser.setContentHandler(handler); sheetParser.parse(sheetSource); } catch(ParserConfigurationException e) { throw new RuntimeException("SAX parser appears to be broken - " + e.getMessage()); } } /** * * @throws IOException If reading the data from the package fails. * @throws SAXException if parsing the XML data fails. * @throws OpenXML4JException */ public void process() throws IOException, OpenXML4JException, SAXException { ReadOnlySharedStringsTable strings = new ReadOnlySharedStringsTable(this.xlsxPackage); XSSFReader xssfReader = new XSSFReader(this.xlsxPackage); StylesTable styles = xssfReader.getStylesTable(); XSSFReader.SheetIterator iter = (XSSFReader.SheetIterator) xssfReader.getSheetsData(); while (iter.hasNext()) { try (InputStream stream = iter.next()) { processSheet(styles, strings, new SheetToMap(), stream); } } } } ```
Un ejemplo de cómo llamarla sería este:
import java.io.InputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.LinkedList;
import java.util.Map;
import java.util.function.Function;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.ContentHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import lombok.RequiredArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import lombok.NonNull;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.openxml4j.opc.PackageAccess;
import org.apache.poi.ss.util.CellAddress;
import org.apache.poi.ss.util.CellReference;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.util.XMLHelper;
import org.apache.poi.xssf.eventusermodel.XSSFReader;
import org.apache.poi.xssf.eventusermodel.ReadOnlySharedStringsTable;
import org.apache.poi.xssf.eventusermodel.XSSFSheetXMLHandler;
import org.apache.poi.xssf.eventusermodel.XSSFSheetXMLHandler.SheetContentsHandler;
import org.apache.poi.xssf.model.Styles;
import org.apache.poi.xssf.model.StylesTable;
import org.apache.poi.xssf.model.SharedStrings;
import org.apache.poi.xssf.usermodel.XSSFComment;
@RequiredArgsConstructor
@Getter
@Setter
public class ExcelToMap{
private static final Logger LOGGER = LogManager.getLogger(ExcelToMap.class);
private class SheetToMap implements SheetContentsHandler {
private boolean firstCellOfRow;
private int currentRow = -1;
private int currentCol = -1;
private List<String> key;
private List<Double> value;
public SheetToMap(){
currentRow = -1;
currentCol = -1;
firstCellOfRow = false;
}
@Override
public void startRow(int rowNum){
firstCellOfRow = true;
currentRow = rowNum;
currentCol = -1;
key = new LinkedList<>();
value = new LinkedList<>();
}
@Override
public void endRow(int rowNum){
if (rowNum == 0)
return;
map.merge(key, value, (value1, value2) -> {
List<Double> mergedValue = new LinkedList<>();
ListIterator<Double> iterator1 = value1.listIterator();
ListIterator<Double> iterator2 = value2.listIterator();
while(iterator1.hasNext() && iterator2.hasNext()){
mergedValue.add(iterator1.next() + iterator2.next());
}
return mergedValue;
});
LOGGER.trace(String.format("Row %d parsed",rowNum));
}
@Override
public void cell(String cellReference, String formattedValue, XSSFComment comment){
if (currentRow == 0)
return;
if (firstCellOfRow) {
firstCellOfRow = false;
}
if (cellReference == null) {
cellReference = new CellAddress(currentRow, currentCol).formatAsString();
}
if (formattedValue == null) {
return;
}
currentCol = (new CellReference(cellReference)).getCol();
if(valuesIndexs.contains(currentCol)){
try{
value.add(parseValueFunction.apply(formattedValue));
LOGGER.trace(String.format("Cell %s parsed",cellReference));
}
catch(Exception e){
value.add(0.0);
LOGGER.warn(String.format("Value corresponding to %d collum from key %s is corrupted.",
currentCol, key));
}
} else if (keysIndexs.contains(currentCol)){
key.add(formattedValue);
LOGGER.trace(String.format("Cell %s parsed",cellReference));
} else
return;
}
}
@NonNull private OPCPackage xlsxPackage;
@NonNull private Map<List<String>,List<Double>> map;
@NonNull List<Integer> keysIndexs;
@NonNull List<Integer> valuesIndexs;
@NonNull Function<String, Double> parseValueFunction;
/**
*
* @param styles The table of styles that may be referenced by cells in the sheet
* @param strings The table of strings that may be referenced by cells in the sheet
* @param sheetInputStream The stream to read the sheet-data from.
* @throws java.io.IOException An IO exception from the parser,
* possibly from a byte stream or character stream
* supplied by the application.
* @throws SAXException if parsing the XML data fails.
*/
public void processSheet(Styles styles, SharedStrings strings, SheetContentsHandler sheetHandler,
InputStream sheetInputStream) throws IOException, SAXException {
DataFormatter formatter = new DataFormatter(true);
InputSource sheetSource = new InputSource(sheetInputStream);
try {
XMLReader sheetParser = XMLHelper.newXMLReader();
ContentHandler handler = new XSSFSheetXMLHandler(styles, null, strings, sheetHandler, formatter, false);
sheetParser.setContentHandler(handler);
sheetParser.parse(sheetSource);
} catch(ParserConfigurationException e) {
throw new RuntimeException("SAX parser appears to be broken - " + e.getMessage());
}
}
/**
*
* @throws IOException If reading the data from the package fails.
* @throws SAXException if parsing the XML data fails.
* @throws OpenXML4JException
*/
public void process() throws IOException, OpenXML4JException, SAXException {
ReadOnlySharedStringsTable strings = new ReadOnlySharedStringsTable(this.xlsxPackage);
XSSFReader xssfReader = new XSSFReader(this.xlsxPackage);
StylesTable styles = xssfReader.getStylesTable();
XSSFReader.SheetIterator iter = (XSSFReader.SheetIterator) xssfReader.getSheetsData();
while (iter.hasNext()) {
try (InputStream stream = iter.next()) {
processSheet(styles, strings, new SheetToMap(), stream);
}
}
}
}
Un ejemplo de cómo llamarla sería este: