File upload excel file

First, read the excel file

    /**
     * 读取excel
     * @param file
     * @return
     * @throws IOException
     */
    public static List<List<Object>> readExcel(MultipartFile file) throws IOException {
        String extension = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1).toLowerCase();

        if ("xls".equals(extension)) {
            return read2003Excel(file.getInputStream());
        } else if ("xlsx".equals(extension)) {
            return read2007Excel(file.getInputStream());
        } else {
            throw new IOException("不支持的文件类型");
        }
    }

    /**
     * 读取 office 2003 excel
     * @param stream
     * @return
     * @throws IOException
     */
    private static List<List<Object>> read2003Excel(InputStream stream) throws IOException {
        List<List<Object>> list = new LinkedList<List<Object>>();
        HSSFWorkbook hwb = newHSSFWorkbook (Stream); 
        HSSFSheet Sheet = hwb.getSheetAt (0 ); 
        Object value = null ; 
        HSSFRow Row = null ; 
        HSSFCell Cell = null ; 
        DecimalFormat DF = new new DecimalFormat ( "0"); // formatting character number String 
        SimpleDateFormat sdf = new new the SimpleDateFormat ( "the MM-dd-YYYY"); // formatted date string 
        DecimalFormat NF = new new DecimalFormat ( "### ####."); // format numbers
         // The first row is the header the second row is the column name, start reading from the third row
        for ( int I = sheet.getFirstRowNum () + 2; I <= sheet.getPhysicalNumberOfRows (); I ++ ) { 
            Row = sheet.getRow (I);
             IF (Row == null ) {
                 Continue ; 
            } 
            // check for lines the number of spaces, the number is less than the last one has demonstrated one or more spaces, but not the entire line 
            IF (CheckRowNull (row) < row.getLastCellNum ()) { 
                List <Object> linked = new new the LinkedList <Object> ();
                 for ( int J = row.getFirstCellNum (); J <= row.getLastCellNum (); J ++ ) { 
                    Cell= row.getCell(j);
                    if (cell == null) {
                        linked.add("");
                        continue;
                    }
                    switch (cell.getCellType()) {
                        case XSSFCell.CELL_TYPE_STRING:
                            value = cell.getStringCellValue();
                            break;
                        case XSSFCell.CELL_TYPE_NUMERIC:
                            if ("@".equals(cell.getCellStyle().getDataFormatString())) {
                                value = df.format(cell.getNumericCellValue());
                            } else if ("General".equals(cell.getCellStyle().getDataFormatString())) {
                                value = nf.format(cell.getNumericCellValue());
                            } else {
                                value = sdf.format(HSSFDateUtil.getJavaDate(cell.getNumericCellValue()));
                            }
                            break;
                        case XSSFCell.CELL_TYPE_BOOLEAN:
                            value = cell.getBooleanCellValue();
                            break;
                        case XSSFCell.CELL_TYPE_BLANK:
                            value = "";
                            break;
                        default:
                            value = cell.toString();
                    }
                    if (value == null || "".equals(value)) {
                        linked.add("");
                        continue;
                    }
                    linked.add(value);
                }
                list.add(linked);
            }
        }
        return List; 
    } 

    / ** 
     * Excel 2007 reads the Office 
     * @param Stream 
     * @return 
     * @throws IOException
      * / 
    Private  static List <List <Object >> (the InputStream Stream) read2007Excel throws IOException { 
        List <List <Object >> = List new new the LinkedList <List <>> Object ();
         // configured XSSFWorkbook objects, strPath incoming file path 
        XSSFWorkbook XWB = new new (Stream) XSSFWorkbook;
         // read the first chapter the table of contents 
        XSSFSheet sheet = xwb.getSheetAt (0 ); 
        Object value = null ; 
        XSSFRow Row = null ; 
        XSSFCell the Cell = null ; 
        DecimalFormat df = new new DecimalFormat ( "0"); // formatted number String character 
        SimpleDateFormat = SDF new new the SimpleDateFormat ( "the MM-dd-YYYY"); // formatted date string 
        DecimalFormat NF = new new DecimalFormat ( "### ####."); // format numbers
         // first line is title, the second row is the column name from the third row to start reading 
        for ( int i = sheet.getFirstRowNum() + 2; i <= sheet.getPhysicalNumberOfRows(); i++) {
            row = sheet.getRow(i);
            if (row == null) {
                continue;
            }
            if(CheckXSSFRowNull(row) < row.getLastCellNum()){
                List<Object> linked = new LinkedList<Object>();
                for (int j = row.getFirstCellNum(); j <= row.getLastCellNum(); j++) {
                    cell = row.getCell(j);
                    if (cell == null) {
                        linked.add("");
                        continue;
                    }
                    switch (cell.getCellType()) {
                        case XSSFCell.CELL_TYPE_STRING:
                            value = cell.getStringCellValue();
                            break;
                        case XSSFCell.CELL_TYPE_NUMERIC:
                            if ("@".equals(cell.getCellStyle().getDataFormatString())) {
                                value = df.format(cell.getNumericCellValue());
                            } else if ("General".equals(cell.getCellStyle().getDataFormatString())) {
                                value = nf.format(cell.getNumericCellValue());
                            } else {
                                value = sdf.format(HSSFDateUtil.getJavaDate(cell.getNumericCellValue()));
                            }
                            break;
                        case XSSFCell.CELL_TYPE_BOOLEAN:
                            value = cell.getBooleanCellValue();
                            break;
                        case XSSFCell.CELL_TYPE_BLANK:
                            value = "";
                            break;
                        default:
                            value = cell.toString();
                    }
                    if (value == null || "".equals(value)) {
                        linked.add("");
                        continue;
                    }
                    linked.add(value);
                }
                list.add(linked);
            }
        }
        return list;
    }
//判断读取行为空 2003xls
private static int CheckRowNull(HSSFRow row) {
int num = 0;
Iterator<HSSFCell> cellItr = row.iterator();
while (cellItr.hasNext()) {
HSSFCell c = cellItr.next();
if (c.getCellType() == HSSFCell.CELL_TYPE_BLANK) {
num++;
}
}
return num;
}

//判断读取行为空 2007 xlsx
private static int CheckXSSFRowNull(XSSFRow row) {
int num = 0;
Iterator<Cell> cellItr =row.iterator();
while (cellItr.hasNext()) {
Cell c = cellItr.next();
if (c.getCellType() == HSSFCell.CELL_TYPE_BLANK) {
num++;
}
}
return num;
}
List<List<Object>> lists=ImportsExcel.readExcel(file);    String result = "";try {int row = 0;
            Map<String, Object> m = new HashMap<String, Object>();
            // 获取当前时间
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            // 备注
            String remark="";
            for (List<Object> list : lists) {
                if (list != null && list.size() > 0) {
                    // id
                    m.put("id", IDCode.commonId + IDTool.getWebUserId() + "");
            // get the first column
m.put ( "monitor_date", (String) List.get (0 )); // Get the second column String Place = (String) List.get (. 1 );
            // convert values to database
IF (place.equals ( "a place" )) { place = "0" ; } the else IF (place.equals ( "two places" )) { place = ". 1" ; } the else IF (place.equals ( "Location three " )) { Place =" 2 "; } The else IF (place.equals ( "four places" )) { Place = ". 3" ; } m.put ( "monitor_place" , Place); // Get the third column m.put ( "monitor_equipment", (String ) list.get (2 )); // get the fourth column m.put ( "dust_concentration", (String) list.get (3 )); // get the fifth column m.put ( "inspector_name", (String ) List.get (. 4 ));
            // If the last column has the value
IF (list.size ()>. 5 ) { the remark= (String) List.get (. 5 ); } m.put ( "the remark" , the remark); m.put ( "the create_time" , sdf.format (DATE)); m.put ( "creater_id" , createId); // needs to be changed to a value corresponding to the initial value after circulating the remark = "" ; } Row + = healthDao.addMonitor (m); } IF (Row> =. 1 ) { Result =RequestResponseTool.getJsonMessage (RespCode.commonSucc, RespMsg.commonSucc ); } the else{ result = RequestResponseTool.getJsonMessage(RespCode.commonFail, RespMsg.commonFail); } } catch (Exception e) { rollBack(e, log); result = RequestResponseTool.getJsonMessage(RespCode.commonFail, RespMsg.commonFail); }

 

Guess you like

Origin www.cnblogs.com/flyShare/p/12498451.html