Subversion Repositories Integrator Subversion

Rev

Blame | Last modification | View Log | Download | RSS feed

package br.com.sl.shared;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.DateUtil;

public class ExcelDataUtils {
       
        public static LocalDate lerData(Cell cell) {
        if (cell == null) return null;

        try {
            int t = cell.getCellType();

            // 1) Se for fórmula RTD
            if (t == CellType.FORMULA.getCode()) {
                int ct = cell.getCachedFormulaResultType();

                if (ct == CellType.NUMERIC.getCode()) {
                    double dv = cell.getNumericCellValue();
                    java.util.Date d = DateUtil.getJavaDate(dv);
                    return d.toInstant()
                            .atZone(java.time.ZoneId.systemDefault())
                            .toLocalDate();
                }

                if (ct == CellType.STRING.getCode()) {
                    String text = cell.getStringCellValue().trim();
                    if (text.isEmpty()) return null;

                    DateTimeFormatter[] patterns = {
                            DateTimeFormatter.ofPattern("dd/MM/yyyy"),
                            DateTimeFormatter.ofPattern("dd-MM-yyyy"),
                            DateTimeFormatter.ofPattern("yyyy-MM-dd"),
                            DateTimeFormatter.ofPattern("yyyy/MM/dd")
                    };

                    for (DateTimeFormatter p : patterns) {
                        try {
                            return LocalDate.parse(text, p);
                        } catch (Exception ignored) {}
                    }
                }
            }

            // 2) Se for numérico formatado como data
            if (t == CellType.NUMERIC.getCode() && DateUtil.isCellDateFormatted(cell)) {
                java.util.Date d = cell.getDateCellValue();
                return d.toInstant()
                        .atZone(java.time.ZoneId.systemDefault())
                        .toLocalDate();
            }

            // 3) Se vier como texto
            String text = cell.toString().trim();
            if (text.isEmpty()) return null;

            DateTimeFormatter[] patterns = {
                    DateTimeFormatter.ofPattern("dd/MM/yyyy"),
                    DateTimeFormatter.ofPattern("dd-MM-yyyy"),
                    DateTimeFormatter.ofPattern("yyyy-MM-dd"),
                    DateTimeFormatter.ofPattern("yyyy/MM/dd")
            };

            for (DateTimeFormatter p : patterns) {
                try {
                    return LocalDate.parse(text, p);
                } catch (Exception ignored) {}
            }

        } catch (Exception e) {
            System.out.println("[lerData] erro: " + e.getMessage());
        }

        return null;
    }

    public static LocalTime lerHora(Cell cell) {
        if (cell == null) return null;

        try {
            // 1) Fórmula RTD
            if (cell.getCellType() == CellType.FORMULA.getCode()) {

                if (cell.getCachedFormulaResultType() == CellType.NUMERIC.getCode()) {
                    java.util.Date d = DateUtil.getJavaDate(cell.getNumericCellValue());
                    return d.toInstant()
                            .atZone(java.time.ZoneId.systemDefault())
                            .toLocalTime();
                }

                if (cell.getCachedFormulaResultType() == CellType.STRING.getCode()) {
                    String text = cell.getStringCellValue().trim();
                    if (text.isEmpty()) return null;

                    DateTimeFormatter[] patterns = {
                            DateTimeFormatter.ofPattern("HH:mm:ss"),
                            DateTimeFormatter.ofPattern("H:mm:ss"),
                            DateTimeFormatter.ofPattern("HH:mm"),
                            DateTimeFormatter.ofPattern("H:mm")
                    };

                    for (DateTimeFormatter p : patterns) {
                        try { return LocalTime.parse(text, p); }
                        catch (Exception ignored) {}
                    }
                }
            }

            // 2) Numérico com formato de data/hora
            if (cell.getCellType() == CellType.NUMERIC.getCode() && DateUtil.isCellDateFormatted(cell)) {
                java.util.Date d = cell.getDateCellValue();
                return d.toInstant()
                        .atZone(java.time.ZoneId.systemDefault())
                        .toLocalTime();
            }

            // 3) Texto simples
            String text = cell.toString().trim();
            if (text.isEmpty()) return null;

            DateTimeFormatter[] patterns = {
                    DateTimeFormatter.ofPattern("HH:mm:ss"),
                    DateTimeFormatter.ofPattern("H:mm:ss"),
                    DateTimeFormatter.ofPattern("HH:mm"),
                    DateTimeFormatter.ofPattern("H:mm")
            };

            for (DateTimeFormatter p : patterns) {
                try { return LocalTime.parse(text, p); }
                catch (Exception ignored) {}
            }

        } catch (Exception e) {
            System.out.println("[lerHora] erro: " + e.getMessage());
        }

        return null;
    }


    private BigDecimal lerPreco(Cell cell) {
        if (cell == null) return null;

        try {
            // 1) Fórmula RTD
            if (cell.getCellType() == CellType.FORMULA.getCode()) {

                if (cell.getCachedFormulaResultType() == CellType.NUMERIC.getCode()) {
                    return BigDecimal.valueOf(cell.getNumericCellValue());
                }

                if (cell.getCachedFormulaResultType() == CellType.STRING.getCode()) {
                    String text = cell.getStringCellValue().trim();
                    if (text.isEmpty()) return null;
                    text = text.replace(".", "").replace(",", ".");
                    return new BigDecimal(text);
                }
            }

            // 2) Numérico simples
            if (cell.getCellType() == CellType.NUMERIC.getCode()) {
                return BigDecimal.valueOf(cell.getNumericCellValue());
            }

            // 3) Texto
            String text = cell.toString().trim();
            if (text.isEmpty()) return null;

            text = text.replace(".", "").replace(",", ".");
            return new BigDecimal(text);

        } catch (Exception e) {
            System.out.println("[lerPreco] erro: " + e.getMessage());
        }

        return null;
    }
   
    /**
     * Converte a célula de data/hora do Excel para LocalDateTime.
     */

    private LocalDateTime getLocalDateTime(Cell cell, DateTimeFormatter formatacaoDataTime) {
        if (cell == null) {
            return null;
        }

        // Caso seja data/hora numérica do Excel
        if (cell.getCellType() == CellType.NUMERIC.getCode() && DateUtil.isCellDateFormatted(cell)) {
            Date date = cell.getDateCellValue(); // disponível em todas as versões
            if (date == null) {
                return null;
            }
            return date.toInstant()
                       .atZone(ZoneId.systemDefault())
                       .toLocalDateTime();
        }

        // Caso venha como TEXT (por exemplo num CSV importado)
        if (cell.getCellType() == CellType.STRING.getCode()) {
            String text = cell.getStringCellValue();
            if (text == null || text.trim().isEmpty()) {
                return null;
            }
            text = text.trim();
            try {
                // Ajuste o pattern se seu Excel estiver em outro formato
                return LocalDateTime.parse(text, formatacaoDataTime);
            } catch (Exception e) {
                return null;
            }
        }
        return null;
    }
   
    /**
     * Converte a célula de data/hora do Excel para LocalDateTime.
     */

    public static LocalDateTime getLocalDateTime(String cell, DateTimeFormatter formatacaoDataTime) {
        if (cell == null || cell.trim().isEmpty()) {
            return null;
        }
        cell = cell.trim();
        try {
            return LocalDateTime.parse(cell, formatacaoDataTime);
        } catch (Exception e) {
            return null;
        }
    }
   
    public static boolean isNumeric(Cell cell) {
        if (cell == null) return false;

        if (cell.getCellType() == CellType.NUMERIC.getCode()) {
            return true;
        }

        if (cell.getCellType() == CellType.STRING.getCode()) {
            try {
                Double.parseDouble(cell.getStringCellValue().replace(",", "."));
                return true;
            } catch (NumberFormatException e) {
                return false;
            }
        }

        return false;
    }

}