package com.ylcm.sys.common;
  
import java.io.File;  
import java.io.FileInputStream;  
import java.util.ArrayList;  
import java.util.HashMap;  
import java.util.List;  
import java.util.Map;  
  
import org.apache.poi.hssf.usermodel.HSSFCell;  
import org.apache.poi.hssf.usermodel.HSSFDateUtil;  
import org.apache.poi.hssf.usermodel.HSSFWorkbook;  
import org.apache.poi.poifs.filesystem.OfficeXmlFileException;  
import org.apache.poi.ss.usermodel.Cell;  
import org.apache.poi.ss.usermodel.Row;  
import org.apache.poi.ss.usermodel.Sheet;  
import org.apache.poi.ss.usermodel.Workbook;  
import org.apache.poi.ss.util.CellRangeAddress;  
import org.apache.poi.xssf.usermodel.XSSFWorkbook;  
  
/** 
 * 操作Excel表格的功能类 
 */  
public class XLSCovertCSVReader {  
    private Sheet sheet;  
    private Row row;  
  
    /** 
     * 读取Excel表格表头的内容 
     * @param InputStream 
     * @return String 表头内容的数组 
     */  
    @SuppressWarnings("resource")
	public String[] readExcelTitle(File file) {  
        String[] title = null;  
        try {  
            Workbook wb = null;  
            try{  
                wb = new HSSFWorkbook(new FileInputStream(file));  
            }catch(OfficeXmlFileException e){  
                wb = new XSSFWorkbook(new FileInputStream(file));  
            }  
          
        sheet = wb.getSheetAt(0);  
        row = sheet.getRow(0);  
        // 标题总列数  
        int colNum = row.getPhysicalNumberOfCells();  
        title = new String[colNum];  
        for (int i = 0; i < colNum; i++) {  
            Cell cell = row.getCell(i);  
            title[i] = cell.getStringCellValue();  
        }  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return title;  
    }  
    /** 
     * 读取Excel所有的sheet页名字 
     * @param InputStream 
     * @return String sheet内容的数组 
     */  
    @SuppressWarnings("resource")
	public String[] readExcelSheetName(File file) {  
        String[] sheetName = null;  
        try {  
            Workbook wb = null;  
            try{  
                wb = new HSSFWorkbook(new FileInputStream(file));  
            }catch(OfficeXmlFileException e){  
                wb = new XSSFWorkbook(new FileInputStream(file));  
            }  
            int maxSheet=wb.getNumberOfSheets();  
            sheetName=new String[maxSheet];  
            for (int i = 0; i < maxSheet; i++) {  
                sheet=wb.getSheetAt(i);  
                sheetName[i]=sheet.getSheetName();  
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return sheetName;  
    }  
      
    public static void main(String[] args) {  
        XLSCovertCSVReader excle=new XLSCovertCSVReader();  
        List<String[]> tmp=excle.readExcelContent("C:\\Users\\Administrator\\Desktop\\节目管理 - 副本.xls",  "节目管理", 7);  
        for (String[] record : tmp) {  
            for (String cell : record) {  
                System.out.print(cell + "  ");  
            }  
            System.out.println();
        }
          
    }  
  
    /** 
     * 读取Excel数据内容 
     * @param InputStream 
     * @return Map 包含单元格数据内容的Map对象 
     */  
    @SuppressWarnings({ "deprecation", "resource" })
	public List<String[]> readExcelContent(String path,String sheetName,int minColumns) {
    	File file = new File(path);
    	List<String[]> content = new ArrayList<String[]>();  
        try {  
            Workbook wb = null;  
            try{  
                wb = new HSSFWorkbook(new FileInputStream(file));  
            }catch(OfficeXmlFileException e){  
                wb = new XSSFWorkbook(new FileInputStream(file));  
            }
            for(int i = 0;i < wb.getNumberOfSheets() ; i ++){
            	Sheet tmp = wb.getSheetAt(i);
            	if(sheetName.equals(tmp.getSheetName())){
            		sheet = tmp;
            	}
            }
            
            // 得到总行数  
            int rowNum = sheet.getLastRowNum()+1;  
            row = sheet.getRow(0);  
            int colNum = row.getPhysicalNumberOfCells();  
            // 正文内容应该从第二行开始,第一行为表头的标题  
            for (int i = 1; i < rowNum; i++) {  
                row = sheet.getRow(i);  
                if(row==null){  
                    break;  
                }  
                String[] list = new String[minColumns];  
                for (int j = 0; j < colNum; j++) {  
                	if(j >= minColumns){//如限制行数  
                        break;  
                    }  
                    Cell cell = row.getCell(j);  
                    if(cell != null) {  
                        switch (cell.getCellType()) {       
                        case HSSFCell.CELL_TYPE_NUMERIC: // 数字       
                            if (HSSFDateUtil.isCellDateFormatted(cell)) {       
                                //如果是date类型则 ，获取该cell的date值       
                                list[j] = (HSSFDateUtil.getJavaDate(cell.getNumericCellValue()).toString());       
                            } else { // 纯数字       
                                double d = cell.getNumericCellValue();  
                                if (d - (int) d < Double.MIN_VALUE) {   
                                // 是否为int型  
                                	list[j] = (Integer.toString((int) d));  
                                } else {   
                                 // 是否为double型  
                                	list[j] = (Double.toString(cell.getNumericCellValue()));  
                                }  
                            }  
                            break;       
                        case HSSFCell.CELL_TYPE_STRING: // 字符串       
                        	list[j] = (cell.getStringCellValue() + "");       
                            break;       
                        case HSSFCell.CELL_TYPE_BOOLEAN: // Boolean       
                        	list[j] = (cell.getBooleanCellValue() + "");       
                            break;       
                        case HSSFCell.CELL_TYPE_FORMULA: // 公式       
                        	list[j] = (cell.getCellFormula() + "");       
                            break;       
                        case HSSFCell.CELL_TYPE_BLANK: // 空值       
                        	list[j] = ("");       
                            break;       
                        case HSSFCell.CELL_TYPE_ERROR: // 故障       
                        	list[j] = ("");       
                            break;       
                        default:       
                        	list[j] = ("");       
                            break;  
                        }  
                    } else {  
                    	list[j] = ("");  
                    }  
                }  
                content.add(list);
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return content;  
    }  
    /** 
     *  
     * @param file  文件 
     * @param maxRow 最大行 -1为不限制 
     * @param maxCell  最大列  -1为不限制 
     * @param startRow 开始行   
     * @param sheetIndex  第几个sheet页 
     * @return 
     */  
    @SuppressWarnings({ "resource", "deprecation" })
	public Map<Integer, List<String>> readExcelContent(File file,int startRow,int sheetIndex) {  
        Map<Integer, List<String>> content = new HashMap<Integer, List<String>>();  
        try {  
            Workbook wb = null;  
            try{  
                wb = new HSSFWorkbook(new FileInputStream(file));  
            }catch(OfficeXmlFileException e){  
                wb = new XSSFWorkbook(new FileInputStream(file));  
            }  
            sheet = wb.getSheetAt(sheetIndex);
            // 得到总行数、总列数  
            int rowNum = sheet.getLastRowNum()+1;  
            row = sheet.getRow(0);  
            int colNum = row.getPhysicalNumberOfCells();  
            // 正文内容应该从第二行开始,第一行为表头的标题  
            for (int i = startRow; i < rowNum; i++) {  
                row = sheet.getRow(i);  
                if(row==null){  
                    break;  
                }  
                if(row.getZeroHeight()==true)  
                {  
                     System.out.println("row("+(i++)+")是隐藏的");  
                     continue;  
                }  
                List<String> list = new ArrayList<String>();  
                for (int j = 0; j < colNum; j++) {  
                    Cell cell = row.getCell(j);  
                      
                    if(cell != null) {  
                          
                        boolean isMerge = isMergedRegion(sheet, i, cell.getColumnIndex());   
                         if(isMerge) {   
                             String rs = getMergedRegionValue(sheet, row.getRowNum(), cell.getColumnIndex());   
                             list.add(rs);       
                         }else{  
                             switch (cell.getCellType()) {       
                            case HSSFCell.CELL_TYPE_NUMERIC: // 数字       
                                if (HSSFDateUtil.isCellDateFormatted(cell)) {       
                                    //如果是date类型则 ，获取该cell的date值       
                                    list.add(HSSFDateUtil.getJavaDate(cell.getNumericCellValue()).toString());       
                                } else { // 纯数字       
                                    double d = cell.getNumericCellValue();  
                                    if (d - (int) d < Double.MIN_VALUE) {   
                                        // 是否为int型  
                                        list.add(Integer.toString((int) d));  
                                    } else {   
                                        // 是否为double型  
                                        list.add(Double.toString(cell.getNumericCellValue()));  
                                    }  
                                }  
                                break;       
                            case HSSFCell.CELL_TYPE_STRING: // 字符串       
                                list.add(cell.getStringCellValue() + "");       
                                break;       
                            case HSSFCell.CELL_TYPE_BOOLEAN: // Boolean       
                                list.add(cell.getBooleanCellValue() + "");       
                                break;       
                            case HSSFCell.CELL_TYPE_FORMULA: // 公式       
                                list.add(cell.getCellFormula() + "");       
                                break;       
                            case HSSFCell.CELL_TYPE_BLANK: // 空值       
                                list.add("");       
                                break;       
                            case HSSFCell.CELL_TYPE_ERROR: // 故障       
                                list.add("");       
                                break;       
                            default:       
                                list.add("");       
                                break;  
                        }  
                               
                         }  
                          
                    } else {  
                        list.add("");  
                    }  
                }  
                content.put(i, list);  
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return content;  
    }  
  
    /** 
     * 获取单元格数据内容为字符串类型的数据 
     *  
     * @param cell Excel单元格 
     * @return String 单元格数据内容 
     */  
    @SuppressWarnings({ "deprecation", "unused" })
	private String getStringCellValue(HSSFCell cell) {  
        String strCell = "";  
        switch (cell.getCellType()) {  
        case HSSFCell.CELL_TYPE_STRING:  
            strCell = cell.getStringCellValue();  
            break;  
        case HSSFCell.CELL_TYPE_NUMERIC:  
            strCell = String.valueOf(cell.getNumericCellValue());  
            break;  
        case HSSFCell.CELL_TYPE_BOOLEAN:  
            strCell = String.valueOf(cell.getBooleanCellValue());  
            break;  
        case HSSFCell.CELL_TYPE_BLANK:  
            strCell = "";  
            break;  
        default:  
            strCell = "";  
            break;  
        }  
        if (strCell.equals("") || strCell == null) {  
            return "";  
        }  
        if (cell == null) {  
            return "";  
        }  
        return strCell;  
    }  
    /** 
     * 是否为单元格 
     * @param sheet 
     * @param row 
     * @param column 
     * @return 
     */  
    private boolean isMergedRegion(Sheet sheet,int row ,int column) {     
        int sheetMergeCount = sheet.getNumMergedRegions();     
        for (int i = 0; i < sheetMergeCount; i++) {     
              CellRangeAddress range = sheet.getMergedRegion(i);     
              int firstColumn = range.getFirstColumn();   
              int lastColumn = range.getLastColumn();     
              int firstRow = range.getFirstRow();     
              int lastRow = range.getLastRow();     
              if(row >= firstRow && row <= lastRow){   
                      if(column >= firstColumn && column <= lastColumn){   
                              return true;     
                          }   
              }     
        }   
        return false;     
      }   
    /**     
     * 获取合并单元格的值     
     * @param sheet     
     * @param row     
     * @param column     
     * @return     
     */       
     public String getMergedRegionValue(Sheet sheet ,int row , int column){       
         int sheetMergeCount = sheet.getNumMergedRegions();       
                
         for(int i = 0 ; i < sheetMergeCount ; i++){       
             CellRangeAddress ca = sheet.getMergedRegion(i);       
             int firstColumn = ca.getFirstColumn();       
             int lastColumn = ca.getLastColumn();       
             int firstRow = ca.getFirstRow();       
             int lastRow = ca.getLastRow();       
             if(row >= firstRow && row <= lastRow){       
                  if(column >= firstColumn && column <= lastColumn){       
                     Row fRow = sheet.getRow(firstRow);   
                     Cell fCell = fRow.getCell(firstColumn);   
                     return getCellValue(fCell) ;   
                 }       
             }       
         }       
                
         return null ;       
     }     
     /**     
      * 获取单元格的值     
      * @param cell     
      * @return     
      */       
    @SuppressWarnings("deprecation")
	public String getCellValue(Cell cell){       
                 
          if(cell == null) return " ";       
                 
          if(cell.getCellType() == Cell.CELL_TYPE_STRING){       
                     
              return cell.getStringCellValue();       
                     
          }else if(cell.getCellType() == Cell.CELL_TYPE_BOOLEAN){       
                     
              return String.valueOf(cell.getBooleanCellValue());       
                     
          }else if(cell.getCellType() == Cell.CELL_TYPE_FORMULA){       
                     
              return cell.getCellFormula() ;       
                     
          }else if(cell.getCellType() == Cell.CELL_TYPE_NUMERIC){       
                     
              return String.valueOf(cell.getNumericCellValue());       
                     
          }       
          return " ";       
      }   
}  