package com.ssm.core.util;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;

public class ExcelUtils {




    public static Workbook readExcel(String filePath) throws IOException {
        Workbook wb = null;
        if(filePath==null){
            return null;
        }
        String extString = filePath.substring(filePath.lastIndexOf("."));
        InputStream is = null;
            is = new FileInputStream(filePath);
            if(".xls".equals(extString)){
                wb = new HSSFWorkbook(is);
            }else if(".xlsx".equals(extString)){
                wb = new XSSFWorkbook(is);
            }else{
                wb = null;
            }

        return wb;
    }


    public static Workbook readExcel(String fileName,InputStream inputStream) throws IOException {
        if(fileName.endsWith(".xls")){
            return new HSSFWorkbook(inputStream);
        }else if(fileName.endsWith(".xlsx")){
            return new XSSFWorkbook(inputStream);
        }else{
            return null;
        }
    }


    public static Object getCellValue(Cell cell){
        Object value = null;
        DecimalFormat df = new DecimalFormat("0");  //格式化number String字符
        SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd");  //日期格式化
        DecimalFormat df2 = new DecimalFormat("0.00");  //格式化数字
        if(cell.getCellTypeEnum().equals(CellType.STRING)){
            value = cell.getRichStringCellValue().getString();
        }else if(cell.getCellTypeEnum().equals(CellType.NUMERIC)){
            if("General".equals(cell.getCellStyle().getDataFormatString())){
                value = df.format(cell.getNumericCellValue());
            }else if("m/d/yy".equals(cell.getCellStyle().getDataFormatString())){
                value = sdf.format(cell.getDateCellValue());
            }else{
                value = df2.format(cell.getNumericCellValue());
            }
        }else if(cell.getCellTypeEnum().equals(CellType.BOOLEAN)){
            value = cell.getBooleanCellValue();
//        }else if(cell.getCellTypeEnum().equals(CellType.BLANK)){

        }

        return value;
    }

}

