package cn.com.countrygarden.bi.main.util;

import cn.com.countrygarden.bi.main.exception.ServiceException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileInputStream;

public class WorkbookUtil {

    public static Workbook readFromFile(String file) {
        Workbook workbook = null;

        try {
            FileInputStream inputStream = new FileInputStream(file);
            workbook = isExcel2003(file)
                    ? (new HSSFWorkbook(inputStream))
                    : (new XSSFWorkbook(inputStream));
        } catch (Exception e) {
            throw new ServiceException("无法解析的 Excel 文件：" + e.getMessage());
        }

        return workbook;
    }

    // @描述：是否是2003的excel，返回true是2003
    public static boolean isExcel2003(String filePath) {
        return filePath.matches("^.+\\.(?i)(xls)$");
    }

    //@描述：是否是2007的excel，返回true是2007
    public static boolean isExcel2007(String filePath) {
        return filePath.matches("^.+\\.(?i)(xlsx)$");
    }
}
