【转】上传并解析excel

【转载自】http://blog.csdn.net/u011563331/article/details/51322523

通过解析excel,将数据存储到数据库中。现在将方法保存下来。

使用的是apache的poi组件。

 

public List<String[]> paseUserStoryFile(MultipartFile file) {
        List<String[]> list = new ArrayList<String[]>();
        try {
            POIFSFileSystem pois = new POIFSFileSystem(file.getInputStream());
            //新建WorkBook
            HSSFWorkbook wb = new HSSFWorkbook(pois);
            //获取Sheet(工作薄)总个数
            int sheetNumber = wb.getNumberOfSheets();
            for (int i = 0; i < sheetNumber; i++) {
                //获取Sheet(工作薄)
                HSSFSheet sheet = wb.getSheetAt(i);
                //开始行数
                int firstRow = sheet.getFirstRowNum();
                //结束行数
                int lastRow = sheet.getLastRowNum();
                //判断该Sheet(工作薄)是否为空
                boolean isEmpty = false;
                if(firstRow == lastRow){
                    isEmpty = true;
                }
                 
                if(!isEmpty){
                    for (int j = firstRow+1; j <= lastRow; j++) {
                        //获取一行
                        HSSFRow row = sheet.getRow(j);
                        //开始列数
                        int firstCell = row.getFirstCellNum();
                        //结束列数
                        int lastCell = row.getLastCellNum();
                        //判断该行是否为空
                        String[] value = new String[lastCell]; 
                        if(firstCell != lastCell){
                            for (int k = firstCell; k < lastCell; k++) {
                                
                                
                                
                                //获取一个单元格
                                HSSFCell cell = row.getCell(k);
                                Object str = null;
                                //获取单元格,值的类型
                                int cellType = cell.getCellType();
                                
                                if(cellType == 0){
                                    str = cell.getNumericCellValue();
                                }else if(cellType == 1){
                                    str = cell.getStringCellValue();
                                }else if(cellType == 2){
                                }else if(cellType == 4){
                                    str = cell.getBooleanCellValue();
                                }
                              value[k] = (String) str;
                            }
                             
                        }
                        //每一行循环完对应的就是一个用户故事的所有属性全部拿到
                        list.add(value);  
                    }
                     
                }
                 
            }
        } catch (IOException e) {
            
            e.printStackTrace();
        }
        return list;
    }

posted @ 2016-07-27 23:56  ne_lucifer  阅读(207)  评论(0编辑  收藏  举报