导入数据的工具类

package com.yaming.hst.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
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.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import jcifs.smb.SmbFile;
import jcifs.smb.SmbFileInputStream;

/**
 * 
 * @author 
 *
 */
public class ExcelUtils {
    
    private final static String excel2003L =".xls";    //2003- 版本的excel  
    private final static String excel2007U =".xlsx";   //2007+ 版本的excel 

    /**
     * 修改excel某个单元值 (如果版本为excel2007, 将所有的XSSFWorkbook改成HSSFWorkbook)
     * 
     * @param fileToBeRead
     * @param sheet
     * @param row
     * @param column
     * @param updateValue
     */
    public static void modifyCell(String fileToBeRead, String sheet, short row, short column, String updateValue) {

        try {
            XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(fileToBeRead));

            XSSFCell cell = workbook.getSheet(sheet).getRow(row).getCell(column);

            cell.setCellValue(updateValue);

            FileOutputStream out = null;
            try {
                out = new FileOutputStream(fileToBeRead);
                workbook.write(out);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static XSSFWorkbook getWorkBook(String fileToBeRead) {

        try {
            XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(fileToBeRead));
            return workbook;
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }
    }

    public static HSSFWorkbook getHSSFWorkBook(String fileToBeRead) {
        File file = new File(fileToBeRead);
        if(file.exists()){
            try {
                HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(fileToBeRead));
                return workbook;
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return null;
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return null;
            }
        }
        return null;
    }
    
    public static XSSFWorkbook getXSSFWorkBook(String fileToBeRead) {
        File file = new File(fileToBeRead);
        if(file.exists()){
            try {
                XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(fileToBeRead));
                return workbook;
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return null;
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return null;
            }
        }
        return null;
    }
    

    public static XSSFWorkbook getRemoteWorkBook(String remoteUrl) {

        try {
            SmbFile remoteFile = new SmbFile(remoteUrl);
            XSSFWorkbook workbook = new XSSFWorkbook(new SmbFileInputStream(remoteFile));
            return workbook;
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 通过对单元格遍历的形式来获取信息 ,这里要判断单元格的类型才可以取出值
     * 
     * @param filePath
     *            excel文件路径
     * @param sheetIndex
     *            sheet标签,第几个sheet页,从0开始
     * @return
     * @throws Exception
     */
    public static String[][] readTable(File file, int sheetIndex) throws Exception {
        XSSFWorkbook wb = null;
        try {
            InputStream ips = new FileInputStream(file);
            wb = new XSSFWorkbook(ips);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        XSSFSheet sheet = wb.getSheetAt(sheetIndex);
        String[][] excelContents = null;
        int rowNum = sheet.getLastRowNum()+1;
        int cellNum =0;
        for (int i = 0; i < rowNum; i++) {
            XSSFRow row = sheet.getRow(i);
            if(row == null) continue;
            //防止前几行为空
            cellNum = row.getPhysicalNumberOfCells();
            if(cellNum != 0) break;
        }
        //excelContents = new String[rowNum][cellNum];
        List<List<String>> tableList = new ArrayList<List<String>>();
        for (int i = 0; i < rowNum; i++) {
            List<String> rowList = new ArrayList<String>();
            XSSFRow row = sheet.getRow(i);
            if(row == null){
                //有一行为空
                continue;
            }
            for (int j = 0; j < cellNum; j++) {
                XSSFCell cell = row.getCell(j);
                if(cell == null ){
                    //某一单元格为空
                     //excelContents[i][j] = "";
                    rowList.add("");
                     continue;
                }
                switch (cell.getCellType()) {
                case XSSFCell.CELL_TYPE_BOOLEAN:
                    // 得到Boolean对象的方法 |
//                    excelContents[i][j] = (cell.getBooleanCellValue() == true ? "Y" : "N");
                    rowList.add(cell.getBooleanCellValue() == true ? "Y" : "N");
                    break;
                case XSSFCell.CELL_TYPE_NUMERIC:
                    // 先看是否是日期格式
                    if (HSSFDateUtil.isCellDateFormatted(cell)) {
                        // 读取日期格式
                        Date date = cell.getDateCellValue();
                        if (date != null) {
                            //excelContents[i][j] = new SimpleDateFormat("yyyy-MM-dd").format(date);
                            rowList.add(new SimpleDateFormat("yyyy-MM-dd").format(date));
                        } else {
                            //excelContents[i][j] = "";
                            rowList.add("");
                        }
                    } else {
                        // 读取数字
                        //excelContents[i][j] = new DecimalFormat("0").format(cell.getNumericCellValue());
                        //excelContents[i][j] = cell.getNumericCellValue()+"";
                        cell.setCellType(Cell.CELL_TYPE_STRING);
                        rowList.add( cell.getStringCellValue());
                    }
                    break;
                case XSSFCell.CELL_TYPE_FORMULA:
                    // 读取公式
                    try {
//                        excelContents[i][j] = cell.getStringCellValue();
                        rowList.add(cell.getStringCellValue());
                    } catch (IllegalStateException e) {
                        //excelContents[i][j] = String.valueOf(cell.getNumericCellValue());
                        try {
                            cell.setCellType(Cell.CELL_TYPE_STRING);
                            rowList.add( cell.getStringCellValue());
                        } catch (Exception e1) {
                            rowList.add("");
                        }
                    }
                    break;
                case XSSFCell.CELL_TYPE_STRING:
                    // 读取String
                    //excelContents[i][j] = cell.getRichStringCellValue().toString();
                    rowList.add(cell.getRichStringCellValue().toString());
                    break;
                case XSSFCell.CELL_TYPE_BLANK:
                    //excelContents[i][j] ="";
                    rowList.add("");
                }
            }
            tableList.add(rowList);
        }
        
        Iterator<List<String>> iterator = tableList.iterator();
        while (iterator.hasNext()) {
            List<java.lang.String> list = (List<java.lang.String>) iterator.next();
            boolean flag = false;
            for (String value : list) {
                //判断当前行是否是空白行
                if(StringUtils.isNotBlank(value))
                    flag = true;//如果当前行有数据就不删除
            }
            if(!flag) iterator.remove();//如果当前行没有内容,删除此行
        }
        excelContents = new String[tableList.size()][cellNum];
        for (int i = 0; i < tableList.size(); i++) {
            List<String> list = tableList.get(i);
            for (int j = 0; j < list.size(); j++) {
                excelContents[i][j] = list.get(j);
            }
        }
        
        /*
         * for(Iterator ite=sheet.rowIterator();ite.hasNext();){ XSSFRow
         * row=(XSSFRow) ite.next(); System.out.println(); for(Iterator
         * itet=row.cellIterator();itet.hasNext();){ XSSFCell cell=(XSSFCell)
         * itet.next(); switch(cell.getCellType()){ case
         * XSSFCell.CELL_TYPE_BOOLEAN: //得到Boolean对象的方法
         * System.out.print(cell.getBooleanCellValue()+" "); break; case
         * XSSFCell.CELL_TYPE_NUMERIC: //先看是否是日期格式
         * if(HSSFDateUtil.isCellDateFormatted(cell)){ //读取日期格式
         * System.out.print(cell.getDateCellValue()+" "); }else{ //读取数字
         * System.out.print(cell.getNumericCellValue()+" "); } break; case
         * XSSFCell.CELL_TYPE_FORMULA: //读取公式
         * System.out.print(cell.getCellFormula()+" "); break; case
         * XSSFCell.CELL_TYPE_STRING: //读取String
         * System.out.print(cell.getRichStringCellValue().toString()+" ");
         * break; } } }
         */
        return excelContents;

    }

    public static String[][] readExcel(InputStream in, String fileName,int sheetIndex) throws Exception {
        Workbook wb = getWorkbook(in,fileName);
        Sheet sheet = wb.getSheetAt(sheetIndex);
        String[][] excelContents = null;
        int rowNum = sheet.getLastRowNum()+1;
        if (rowNum >= 10000) {
            rowNum = 10000;
        }
        int cellNum =0;
        for (int i = 0; i < rowNum; i++) {
            Row row = sheet.getRow(i);
            if(row == null) continue;
            //防止前几行为空
            cellNum = row.getPhysicalNumberOfCells();
            if(cellNum != 0) break;
        }
        List<List<String>> tableList = new ArrayList<List<String>>();
        for (int i = 0; i < rowNum; i++) {
            List<String> rowList = new ArrayList<String>();
            Row row = sheet.getRow(i);
            if(row == null){
                //有一行为空
                continue;
            }
            for (int j = 0; j < cellNum; j++) {
                Cell cell = row.getCell(j);
                if(cell == null ){
                    //某一单元格为空
                    rowList.add("");
                     continue;
                }
                switch (cell.getCellType()) {
                case Cell.CELL_TYPE_BOOLEAN:
                    // 得到Boolean对象的方法 
                    rowList.add(cell.getBooleanCellValue() == true ? "Y" : "N");
                    break;
                case Cell.CELL_TYPE_NUMERIC:
                    // 先看是否是日期格式
                    if (HSSFDateUtil.isCellDateFormatted(cell)) {
                        // 读取日期格式
                        Date date = cell.getDateCellValue();
                        if (date != null) {
                            rowList.add(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date));
                        } else {
                            rowList.add("");
                        }
                    } else {
                        // 读取数字
                        cell.setCellType(Cell.CELL_TYPE_STRING);
                        rowList.add( cell.getStringCellValue());
                    }
                    break;
                case Cell.CELL_TYPE_FORMULA:
                    // 读取公式
                    try {
                        rowList.add(cell.getStringCellValue());
                    } catch (IllegalStateException e) {
                        try {
                            cell.setCellType(Cell.CELL_TYPE_STRING);
                            rowList.add(cell.getStringCellValue());
                        } catch (Exception e1) {
                            rowList.add("");
                        }
                    }
                    break;
                case Cell.CELL_TYPE_STRING:
                    rowList.add(cell.getRichStringCellValue().toString());
                    break;
                case Cell.CELL_TYPE_BLANK:
                    rowList.add("");
                }
            }
            tableList.add(rowList);
        }
        
        Iterator<List<String>> iterator = tableList.iterator();
        while (iterator.hasNext()) {
            List<java.lang.String> list = (List<java.lang.String>) iterator.next();
            boolean flag = false;
            for (String value : list) {
                //判断当前行是否是空白行
                if(StringUtils.isNotBlank(value))
                    flag = true;//如果当前行有数据就不删除
            }
            if(!flag) iterator.remove();//如果当前行没有内容,删除此行
        }
        excelContents = new String[tableList.size()][cellNum];
        for (int i = 0; i < tableList.size(); i++) {
            List<String> list = tableList.get(i);
            for (int j = 0; j < list.size(); j++) {
                excelContents[i][j] = list.get(j);
            }
        }
        return excelContents;
    }
    
    
    
     /** 
     * 描述:根据文件后缀,自适应上传文件的版本  
     * @param inStr,fileName 
     * @return 
     * @throws Exception 
     */  
    public static  Workbook getWorkbook(InputStream inStr,String fileName) throws Exception{  
        Workbook wb = null;  
        String fileType = fileName.substring(fileName.lastIndexOf("."));  
        if(excel2003L.equals(fileType)){  
            wb = new HSSFWorkbook(inStr);  //2003-  
        }else if(excel2007U.equals(fileType)){  
            wb = new XSSFWorkbook(inStr);  //2007+
        }else{  
            throw new Exception("解析的文件格式有误!");  
        }  
        return wb;  
    }

    /**
     * Deal with the collapsed cell in vertical direction. 
     * If current cell is empty, try to loop up and find the first non-empty cell as its value.
     * @param file
     * @param line
     * @param col
     * @param header
     * @return
     */
    public static String lookUp(String[][] file, int line, int col, int header){
        if(header < 0)return null;
        if(line <= header) return null;
        if(line > file.length) return null;
        if(col > file[header].length) return null;
        
        for(int i = line ; i > header ; i --){
            String content = file[i][col].trim();
            if(!content.equals("")){
                return content;
            }
        }
        
        return null;
    }

}

猜你喜欢

转载自www.cnblogs.com/inspred/p/9729197.html