Excel压缩成zip导入

阅读更多
@RequestMapping("testImportZip")
    public void testImportZip(MultipartFile file) throws Exception {
    	if(null != file) {
    		InputStream inputStream = file.getInputStream();
    		Charset gbk = Charset.forName("gbk");
    		ZipInputStream zipInputStream  = new ZipInputStream(inputStream,gbk);
    		ZipEntry zipEntry;
    		while((zipEntry = zipInputStream.getNextEntry()) != null) {
    			String name = zipEntry.getName();
    			System.out.println("name=================================================>"+name);
    			long size = zipEntry.getSize();
    			
    			
    			//因为 new HSSFWorkbook(InputStream) new XSSFWorkbook(InputStream)会自动关闭输入流,所以先将 zipInputStream转换一下,防止zipInputStream被关闭
    			ByteArrayOutputStream bout = new ByteArrayOutputStream();
                byte[] temp = new byte[1024];
                byte[] buf = null;
                int length = 0;
                while ((length = zipInputStream.read(temp, 0, 1024)) != -1) {
                    bout.write(temp, 0, length);
                }
                buf = bout.toByteArray();
                bout.close();
                
    			ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(buf);
    			
    			
    			String fileType = name.substring(name.lastIndexOf("."), name.length());
    			HSSFWorkbook hworkbook = null;
	            XSSFWorkbook xworkbook = null;
	            Sheet sheet = null;
    			if(".xls".equalsIgnoreCase(fileType)){
                    hworkbook = new HSSFWorkbook(byteArrayInputStream);
                    sheet = hworkbook.getSheetAt(0);
                }else if(".xlsx".equalsIgnoreCase(fileType)){
                    xworkbook = new XSSFWorkbook(byteArrayInputStream);
                    sheet = xworkbook.getSheetAt(0);
                }
    			if(null != sheet) {
    				//自己的业务
    				for (int i = 2; i <= sheet.getLastRowNum(); i++) {
    					Row row = sheet.getRow(i);
    					if (row != null) {
    						for (Cell cell : row) {
    							String cellvalue;
								if (cell != null) {
									switch (cell.getCellType()) {
									case Cell.CELL_TYPE_NUMERIC: {
										cell.setCellType(Cell.CELL_TYPE_STRING);
										cellvalue = cell.getStringCellValue();
										break;
									}
									case Cell.CELL_TYPE_FORMULA: {
										cellvalue = cell.getCellFormula();
										break;
									}
									case Cell.CELL_TYPE_STRING:
										cellvalue = cell.getStringCellValue();
										break;
									default:
										cellvalue = "";
									}
								} else {
									cellvalue = "";
								}
								System.out.println(cellvalue);
    						}
    					}
    					
    				}
    			}
    			
    		}
    		
    		if(null != zipInputStream) {
    			zipInputStream.close();
    		}
    	}
    	
    }

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

你可能感兴趣的:(Excel压缩成zip导入)