springmvc4整合POI导出Excel的坑

项目中使用springmvc4.1.3+POI实现文件上传

controller层

	@RequestMapping("/excel/exportEnterpriseExcel!exportEnterprise.action") 
	public ResponseEntity exportEnterprise() {
		try {
			String fileName=new String(("企业信息" + System.currentTimeMillis() + ".csv").getBytes("UTF-8"),"iso-8859-1");
			return getInputExcel(fileName);
		} catch (UnsupportedEncodingException e) {
			log.error("UnsupportedEncodingException", e);
		}
		return null;
	}
	
	private ResponseEntity getInputExcel(String filename) {
		String pids = getParameter("pids");
		String exportType = getParameter("exportType");
		HSSFWorkbook wb = new HSSFWorkbook();
		pager = initPager();
		try {
			pager.setPageSize(65530);
			pager.setPageNumber(1);
			wb =  eppEnterpriseService.exportEnterprise(pids,exportType,pager); 
		}catch(Exception e){
			e.printStackTrace();
		}
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
		try {
			wb.write(byteArrayOutputStream);
		} catch (IOException e) {
			e.printStackTrace();
		}
		HttpHeaders headers = new HttpHeaders();  
		headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);  
		headers.setContentDispositionFormData("attachment", filename);  
		return new ResponseEntity(byteArrayOutputStream.toByteArray(),headers,HttpStatus.CREATED);
	}

上面代码省略service与处理Excel的row与cell的过程

springmvc.XML的配置(文本转换器部分)(错误的)

       
          
              
                  
                      
                        
			    text/html;charset=UTF-8
			    text/plain;charset=UTF-8
                            application/json;charset=UTF-8
			  
                      
                  
                
                    
                        
                            application/json;charset=UTF-8
                        
                    
                    
		
              
          
     

因为在controller中使用的返回contentType是MediaType.APPLICATION_OCTET_STREAM,实际上是要将返回的数据处理成application/octet-stream类型。

所以在springmvc的文本转换器中加入这种数据类型的文本转换器即可。

在springmvc.XML中加入

       
          
              
                  
                      
                        
			    text/html;charset=UTF-8
			    text/plain;charset=UTF-8
                            application/json;charset=UTF-8
			  
                      
                  
                
                    
                        
                            application/json;charset=UTF-8
                        
                    
                    
		
		
  			
     				
        				text/plain;charset=UTF-8
     				
  			
		
 
  

你可能感兴趣的:(技术难点总结)