springmvc4整合POI匯出Excel的坑
阿新 • • 發佈:2019-01-05
專案中使用springmvc4.1.3+POI實現檔案上傳
controller層
@RequestMapping("/excel/exportEnterpriseExcel!exportEnterprise.action")
public ResponseEntity<byte[]> 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<byte[]> 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<byte[]>(byteArrayOutputStream.toByteArray(),headers,HttpStatus.CREATED);
}
上面程式碼省略service與處理Excel的row與cell的過程
springmvc.XML的配置(文字轉換器部分)(錯誤的)
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"> <property name="messageConverters"> <list> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> <value>text/plain;charset=UTF-8</value> <value>application/json;charset=UTF-8</value> </list> </property> </bean> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>application/json;charset=UTF-8</value> </list> </property> </bean> </list> </property> </bean>
因為在controller中使用的返回contentType是MediaType.APPLICATION_OCTET_STREAM,實際上是要將返回的資料處理成application/octet-stream型別。
所以在springmvc的文字轉換器中加入這種資料型別的文字轉換器即可。
在springmvc.XML中加入
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"> <property name="messageConverters"> <list> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> <value>text/plain;charset=UTF-8</value> <value>application/json;charset=UTF-8</value> </list> </property> </bean> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>application/json;charset=UTF-8</value> </list> </property> </bean>
<bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/plain;charset=UTF-8</value> </list> </property> </bean></list> </property> </bean>