hssfdateutil.java

来自「EXCEL read and write」· Java 代码 · 共 463 行 · 第 1/2 页

JAVA
463
字号
            return true;        }        return false;    }    /**     * Given a format ID this will check whether the format represents     *  an internal excel date format or not.     * @see #isADateFormat(int, java.lang.String)     */    public static boolean isInternalDateFormat(int format) {            switch(format) {                // Internal Date Formats as described on page 427 in                // Microsoft Excel Dev's Kit...                case 0x0e:                case 0x0f:                case 0x10:                case 0x11:                case 0x12:                case 0x13:                case 0x14:                case 0x15:                case 0x16:                case 0x2d:                case 0x2e:                case 0x2f:                    return true;            }       return false;    }    /**     *  Check if a cell contains a date     *  Since dates are stored internally in Excel as double values     *  we infer it is a date if it is formatted as such.     *  @see #isADateFormat(int, String)     *  @see #isInternalDateFormat(int)     */    public static boolean isCellDateFormatted(HSSFCell cell) {        if (cell == null) return false;        boolean bDate = false;        double d = cell.getNumericCellValue();        if ( HSSFDateUtil.isValidExcelDate(d) ) {            HSSFCellStyle style = cell.getCellStyle();            int i = style.getDataFormat();            String f = style.getDataFormatString(cell.getBoundWorkbook());            bDate = isADateFormat(i, f);        }        return bDate;    }    /**     *  Check if a cell contains a date, checking only for internal     *   excel date formats.     *  As Excel stores a great many of its dates in "non-internal"     *   date formats, you will not normally want to use this method.     *  @see #isADateFormat(int,String)     *  @see #isInternalDateFormat(int)     */    public static boolean isCellInternalDateFormatted(HSSFCell cell) {        if (cell == null) return false;        boolean bDate = false;        double d = cell.getNumericCellValue();        if ( HSSFDateUtil.isValidExcelDate(d) ) {            HSSFCellStyle style = cell.getCellStyle();            int i = style.getDataFormat();            bDate = isInternalDateFormat(i);        }        return bDate;    }    /**     * Given a double, checks if it is a valid Excel date.     *     * @return true if valid     * @param  value the double value     */    public static boolean isValidExcelDate(double value)    {        return (value > -Double.MIN_VALUE);    }    /**     * Given a Calendar, return the number of days since 1900/12/31.     *     * @return days number of days since 1900/12/31     * @param  cal the Calendar     * @exception IllegalArgumentException if date is invalid     */    static int absoluteDay(Calendar cal, boolean use1904windowing)    {        return cal.get(Calendar.DAY_OF_YEAR)               + daysInPriorYears(cal.get(Calendar.YEAR), use1904windowing);    }    /**     * Return the number of days in prior years since 1900     *     * @return    days  number of days in years prior to yr.     * @param     yr    a year (1900 < yr < 4000)     * @param use1904windowing     * @exception IllegalArgumentException if year is outside of range.     */    private static int daysInPriorYears(int yr, boolean use1904windowing)    {        if ((!use1904windowing && yr < 1900) || (use1904windowing && yr < 1900)) {            throw new IllegalArgumentException("'year' must be 1900 or greater");        }        int yr1  = yr - 1;        int leapDays =   yr1 / 4   // plus julian leap days in prior years                       - yr1 / 100 // minus prior century years                       + yr1 / 400 // plus years divisible by 400                       - 460;      // leap days in previous 1900 years        return 365 * (yr - (use1904windowing ? 1904 : 1900)) + leapDays;    }    // set HH:MM:SS fields of cal to 00:00:00:000    private static Calendar dayStart(final Calendar cal)    {        cal.get(Calendar            .HOUR_OF_DAY);   // force recalculation of internal fields        cal.set(Calendar.HOUR_OF_DAY, 0);        cal.set(Calendar.MINUTE, 0);        cal.set(Calendar.SECOND, 0);        cal.set(Calendar.MILLISECOND, 0);        cal.get(Calendar            .HOUR_OF_DAY);   // force recalculation of internal fields        return cal;    }    private static final class FormatException extends Exception {        public FormatException(String msg) {            super(msg);        }    }    /**     * Converts a string of format "HH:MM" or "HH:MM:SS" to its (Excel) numeric equivalent     *     * @return a double between 0 and 1 representing the fraction of the day     */    public static double convertTime(String timeStr) {        try {            return convertTimeInternal(timeStr);        } catch (FormatException e) {            String msg = "Bad time format '" + timeStr                + "' expected 'HH:MM' or 'HH:MM:SS' - " + e.getMessage();            throw new IllegalArgumentException(msg);        }    }    private static double convertTimeInternal(String timeStr) throws FormatException {        int len = timeStr.length();        if (len < 4 || len > 8) {            throw new FormatException("Bad length");        }        String[] parts = TIME_SEPARATOR_PATTERN.split(timeStr);        String secStr;        switch (parts.length) {            case 2: secStr = "00"; break;            case 3: secStr = parts[2]; break;            default:                throw new FormatException("Expected 2 or 3 fields but got (" + parts.length + ")");        }        String hourStr = parts[0];        String minStr = parts[1];        int hours = parseInt(hourStr, "hour", HOURS_PER_DAY);        int minutes = parseInt(minStr, "minute", MINUTES_PER_HOUR);        int seconds = parseInt(secStr, "second", SECONDS_PER_MINUTE);        double totalSeconds = seconds + (minutes + (hours) * 60) * 60;        return totalSeconds / (SECONDS_PER_DAY);    }    /**     * Converts a string of format "YYYY/MM/DD" to its (Excel) numeric equivalent     *     * @return a double representing the (integer) number of days since the start of the Excel epoch     */    public static Date parseYYYYMMDDDate(String dateStr) {        try {            return parseYYYYMMDDDateInternal(dateStr);        } catch (FormatException e) {            String msg = "Bad time format " + dateStr                + " expected 'YYYY/MM/DD' - " + e.getMessage();            throw new IllegalArgumentException(msg);        }    }    private static Date parseYYYYMMDDDateInternal(String timeStr) throws FormatException {        if(timeStr.length() != 10) {            throw new FormatException("Bad length");        }        String yearStr = timeStr.substring(0, 4);        String monthStr = timeStr.substring(5, 7);        String dayStr = timeStr.substring(8, 10);        int year = parseInt(yearStr, "year", Short.MIN_VALUE, Short.MAX_VALUE);        int month = parseInt(monthStr, "month", 1, 12);        int day = parseInt(dayStr, "day", 1, 31);        Calendar cal = new GregorianCalendar(year, month-1, day, 0, 0, 0);        cal.set(Calendar.MILLISECOND, 0);        return cal.getTime();    }    private static int parseInt(String strVal, String fieldName, int rangeMax) throws FormatException {        return parseInt(strVal, fieldName, 0, rangeMax-1);    }    private static int parseInt(String strVal, String fieldName, int lowerLimit, int upperLimit) throws FormatException {        int result;        try {            result = Integer.parseInt(strVal);        } catch (NumberFormatException e) {            throw new FormatException("Bad int format '" + strVal + "' for " + fieldName + " field");        }        if (result < lowerLimit || result > upperLimit) {            throw new FormatException(fieldName + " value (" + result                    + ") is outside the allowable range(0.." + upperLimit + ")");        }        return result;    }}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?