/***
@Title: exportExcelFile
@Description: TODO(直接导出数据源)@param @paramrequest@param @paramresponse@param @paramdataFile 设定文件@returnvoid 返回类型@throws
*/
public static voidexportExcelFile(HttpServletRequest request, HttpServletResponse response, DataFile dataFile) {//String encoding =defaultEncoding;
if (dataFile == null) {return;
}
List> exportData =dataFile.getData();
String fileName=dataFile.getFileName();if (exportData == null || exportData.get(0) == null ||StringUtils.isEmpty(fileName)) {return;
}//if (!StringUtils.isEmpty(dataFile.getEncoding())) {//encoding = dataFile.getEncoding();//}//头处理
Set headerKeySet = new LinkedHashSet<>();
List headerList =dataFile.getHeaderList();if (headerList != null && headerList.size() > 0) {for(Header header : headerList) {
headerKeySet.add(header.getKey());
}
}else{
headerKeySet= exportData.get(0).keySet();
}
InputStream in= null;
OutputStream out= null;//创建workbook
@SuppressWarnings("resource")
HSSFWorkbook workbook= newHSSFWorkbook();//添加Worksheet(不添加sheet时生成的xls文件打开时会报错)
try{//.xls exlce 超过 65536 报错处理 ,拆分多个sheet
int exportPageSize = 20000;int size =exportData.size();int page = size/exportPageSize +1;if (size>exportPageSize) {for (int i = 0; i < page; i++) {
List> subListDate = null;int pageNo =(i+1);if (pageNo * exportPageSize <=size) {
subListDate= exportData.subList(i * exportPageSize, pageNo *exportPageSize);
}else{
subListDate= exportData.subList(i *exportPageSize, size);
}//TODO
HSSFSheet sheet = workbook.createSheet(fileName+pageNo);if (headerKeySet != null) {
createSheet(subListDate, headerKeySet, sheet);
}else{return;
}
}
}else{//TODO
HSSFSheet sheet =workbook.createSheet(fileName);if (headerKeySet != null) {
createSheet(exportData, headerKeySet, sheet);
}else{return;
}
}//response输出
String userAgent = request.getHeader("User-Agent");if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
response.setContentType(CONTENTTYPE_CSV+Constant.CHARSET_UTF_8);
response.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(fileName +FILE_TYPE_XLS, Constant.CHARSET_UTF_8));
}else{//非IE浏览器的处理:
response.setContentType(CONTENTTYPE_CSV +Constant.ISO8859_1);
response.setHeader("Content-Disposition", "attachment; filename=" + new String((fileName +FILE_TYPE_XLS).getBytes(), Constant.ISO8859_1));
}
out=response.getOutputStream();
workbook.write(out);
}catch(Exception e) {
e.printStackTrace();
}finally{try{if (in != null) {
in.close();
}if (out != null) {
out.close();
}
}catch(IOException e) {
in= null;
out= null;
e.printStackTrace();
}
}
}