Skip to content

Instantly share code, notes, and snippets.

@itarocha
Created February 2, 2025 20:42
Show Gist options
  • Save itarocha/1bf7ed612682b01bf4baf01b2a5f5796 to your computer and use it in GitHub Desktop.
Save itarocha/1bf7ed612682b01bf4baf01b2a5f5796 to your computer and use it in GitHub Desktop.
Cache de verificações de Planilha XLS
package br.itarocha.teste.xls;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;
public class ExcelCache {
private static final HashMap<Integer, List<String>> cacheColuna00 = new HashMap<>();
public static void main(String[] args) {
try {
lerPlanilha("/home/itamar/tmp/csv/enderecos.xls");
} catch (Exception e){
throw new RuntimeException(e.getMessage());
}
}
public static void lerPlanilha(String caminhoArquivo) throws IOException {
FileInputStream file = new FileInputStream(caminhoArquivo);
Workbook workbook = WorkbookFactory.create(file);
Sheet sheet = workbook.getSheetAt(0);
Map<Integer, Integer> coluna00 = new HashMap<>();
sheet.forEach(r -> {
r.forEach(c -> {
switch (c.getColumnIndex()) {
case 0:
coluna00.put(c.getRowIndex(), validarCelula(c));
break;
default:
}
});
});
workbook.close();
coluna00.forEach((key, value) -> {
if (!cacheColuna00.get(value).isEmpty()) {
imprimirErros(key+1, cacheColuna00.get(value));
}
});
}
private static int validarCelula(Cell c) {
int hash = 0;
switch (c.getCellType()) {
case BLANK:
hash = makeHash(c.getCellType().name());
cacheColuna00.put(hash, List.of("Coluna não deve ser vazia"));
break;
case STRING:
hash = makeHash(c.getCellType().name() + c.getStringCellValue());
// Validar e receber lista de erros
if (!cacheColuna00.containsKey(hash)) {
String mensagem = null;
String texto = c.getStringCellValue().toUpperCase();
// Adiciona validações
if (!List.of("RUA","AVENIDA","BECO","TRAVESSA","VILA").contains(texto)){
// ERRO
mensagem = String.format("Valor inválido para a coluna ['%s']. " +
"É esperado que seja ['RUA', 'AVENIDA', 'BECO', 'TRAVESSA' OU 'VILA']", c.getStringCellValue());
}
// Só interessa o que não possui erro
cacheColuna00.put(hash, Objects.isNull(mensagem) ? new ArrayList<>() : List.of(mensagem));
}
break;
default:
hash = makeHash("INVALIDO");
String mensagem = String.format("Tipo de célula inválida: [%s] deveria ser STRING", c.getCellType());
cacheColuna00.put(hash, List.of(mensagem));
}
return hash;
}
private static void imprimirErros(int rowIndex, List<String> mensagens) {
mensagens.forEach(m -> System.out.printf("Erro na linha [%d]. Erro: [%s]\n", rowIndex, m));
}
private static int makeHash(final String text){
return text.hashCode();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment