Is there a way to validate the cell format (from excel) to fetch the symbol from it (in Java)?

25 Views Asked by At

Currently I'm reading the cell format from an Excel sheet using style.getDataFormatString(). My goal is to validate this format and extract the currency symbol from it.

As of now, this is the code (Java) and validations are failing for some currency symbols.

public static String getSymbol(String format) {

        if (format.equals("0.00") || format.equals("General"))
            return StringUtils.EMPTY;

        Pattern symbolPattern = Pattern.compile("\\[\\$([^\\-]+)-.*\\]");
        Matcher symbolMatcher = symbolPattern.matcher(format);
        Pattern codePattern = Pattern.compile("\\[\\$(\\w{3})\\]");
        Matcher codeMatcher = codePattern.matcher(format);

        if (symbolMatcher.find()) {
            String symbol = symbolMatcher.group(1);
            return currencyCodeFromSymbol(symbol);
        } else if (codeMatcher.find()) {
            String code = codeMatcher.group(1);
            return code;
        }
        return format;
    }


    private static String currencyCodeFromSymbol(String symbol) {
        for (Currency currency : Currency.getAvailableCurrencies()) {
            if (currency.getSymbol().equals(symbol)) {
                return currency.getCurrencyCode();
            }
        }
        for (Locale locale : Locale.getAvailableLocales()) {
            try {
                Currency CurrLoc = Currency.getInstance(locale);
                if (CurrLoc.getSymbol(locale).equals(symbol)) {
                    return CurrLoc.getCurrencyCode();
                }
            } catch (IllegalArgumentException ignored) {
            }
        }
        return StringUtils.EMPTY;
    }

Expectation is to get the symbol from the cell by using the cell format that has been passed as an argument to getSymbol().

0

There are 0 best solutions below