Java导出excel并下载功能

我们使用的导出并下载功能是利用一个插件叫POI的插件提供的导出功能,很实用;首先先导入Jar包:

Jar包下载地址:http://poi.apache.org/   官方文档地址:http://poi.apache.org/spreadsheet/quick-guide.html

Action代码:

1public void exportToExcel(List<PortalContactVO> data) throws Exception 2 { 3 this.setEnableAccessRequest(true); 4 this.setEnableAccessResponse(true); 5 HttpServletRequest request = this.getRequest(); 6 HttpServletResponse response = this.getResponse(); 7 String randomNumber = request.getParameter("randomNumber");// session名称 8 try { 9 session = request.getSession(); 10 session.setAttribute(randomNumber, new Double(1)); 11 // 导出的EXCEL文件名 12 String exportFileName = "addressBook.xlsx"; 13 response.reset(); 14 response.setContentType("octets/stream"); 15 // response.setHeader("Content-Disposition","attachment;filename="+exportFileName); 16 response.setHeader("Content-Disposition", "attachment;filename=\"" + new String(exportFileName.getBytes("UTF-8"), "iso8859-1") + "\""); 17 18 // 导出的EXCEL列属性 19 List<String> columnListName = new ArrayList<String>(); 20 columnListName.add("userName&姓名"); 21 columnListName.add("mobile&手机"); 22 columnListName.add("shopTel&分店电话"); 23 columnListName.add("postName&职位"); 24 columnListName.add("email&邮箱"); 25 columnListName.add("shopAddress&分店地址"); 26 Bean2ExcelConversionUtils.beans2excelFile07(columnListName, data, response.getOutputStream()); 27 session.setAttribute(randomNumber, new Double(100)); 28 29 } catch (Exception e) { 30 e.printStackTrace(); 31 session.setAttribute(randomNumber, new Double(100)); 32 } catch (Throwable e) { 33 e.printStackTrace(); 34 session.setAttribute(randomNumber, new Double(100)); 35 } 36 }

JSP代码:

1<form id="exportForm"> 2 <input class="btnStyle" type="submit" id="inputExport" value="导出" onclick="exportToExcel()" /> 3 </form> 4 5function exportToExcel() { 6 var randomNumber=new Date().getTime(); 7 top.$.jBox.tip("正在导出...", 'loading'); 8 var exportDate = "${ctx}/xxxAction.do?method=export&randomNumber="+randomNumber; 9 $("#exportForm").attr("action", exportDate); 10 $("#exportForm").attr("method","post"); 11 $("#exportForm").submit(); 12 }

因为是使用的插件,所以需要引入一个工具类(下面的工具类直接复制到新建的类文件里面即可)

也可以通过:http://download.csdn.net/detail/work201003/9404952 进行下载

1import java.beans.Introspector; 2import java.beans.PropertyDescriptor; 3import java.io.File; 4import java.io.FileOutputStream; 5import java.io.IOException; 6import java.io.OutputStream; 7import java.text.SimpleDateFormat; 8import java.util.ArrayList; 9import java.util.Date; 10import java.util.HashMap; 11import java.util.List; 12 13import javax.servlet.http.HttpServletRequest; 14import javax.servlet.http.HttpServletResponse; 15 16import org.apache.poi.hssf.usermodel.HSSFCell; 17import org.apache.poi.hssf.usermodel.HSSFRow; 18import org.apache.poi.hssf.usermodel.HSSFSheet; 19import org.apache.poi.hssf.usermodel.HSSFWorkbook; 20import org.apache.poi.ss.usermodel.Cell; 21import org.apache.poi.ss.usermodel.CellStyle; 22import org.apache.poi.ss.usermodel.Row; 23import org.apache.poi.ss.usermodel.Sheet; 24import org.apache.poi.ss.usermodel.Workbook; 25import org.apache.poi.xssf.streaming.SXSSFSheet; 26import org.apache.poi.xssf.streaming.SXSSFWorkbook; 27 28/** 29 * @author Tan Jiangyong 30 * @date 2013-9-3 下午3:36:43 31 * @version V1.0 32 */ 33@SuppressWarnings("all") 34public class Bean2ExcelConversionUtils { 35 private static final String PATTERN="yyyy-MM-dd HH:mm:ss"; //excel日期格式,默认配置 36 private static final String DATE_PATTERN="yyyy-MM-dd"; //excel日期格式 37 private static final String DATE_HH_PATTERN="HH:mm:ss"; //excel时间格式 38 private static final int TOTAL_SIZE=40000; //每个excel写入多少数据(默认配置) 39 private static final int MAX_SHEET_SIZE=10000; //每一个sheet的大小(默认配置) 40 private static final int COLUMN_WIDTH_WORD=25; //列宽,默认汉字个数为25个 41 private static final int FLUSH_ROWS=100; //每生成excel行数,内存中缓存记录数清空(目的,避免零时文件过大) 42 43 /** 44 * 07、10办公版EXCEL导出(数据直接写到服务器的EXCEL里,以下载的形式,下载导出的数据) 45 * @param listName 列表头名称 46 * @param beans 实体集合 47 * @param result 数字字典Map集 48 * @param filePath 服务器存放文件路径 49 * @param fileName 文件名称 50 * @param totalSize EXCEL条数量 51 * @param maxSheetSize sheet页条数量 52 * @return 文件集合 53 * @throws Exception 54 */ 55 public static <T> List<File> beans2excelFile07(List<String> listName,List<T> beans,HashMap<String,HashMap<String,String>> result,String filePath,String fileName,Integer totalSize,Integer maxSheetSize) throws Exception{ 56 if(totalSize==null || totalSize<=0) 57 totalSize=TOTAL_SIZE; 58 if(maxSheetSize==null || maxSheetSize<=0) 59 maxSheetSize=MAX_SHEET_SIZE; 60 if(fileName==null) 61 fileName=""; 62 return beans2excelFile2007(listName, beans, result, filePath, fileName,totalSize,maxSheetSize); 63 } 64 /** 65 * 07、10办公版EXCEL导出(数据直接写到服务器的EXCEL里,以下载的形式,下载导出的数据) 66 * @param listName 列表头名称 67 * @param beans 实体集合 68 * @param result 数字字典Map集 69 * @param filePath 服务器存放文件路径 70 * @param fileName 文件名称 71 * @param totalSize EXCEL条数量 72 * @param maxSheetSize sheet页条数量 73 * @param request 客户端请求对象 74 * @param response 客户端响应对象 75 * @throws Exception 76 */ 77 public static <T> void beans2excelFile07(List<String> listName,List<T> beans,HashMap<String,HashMap<String,String>> result,String filePath,String fileName,Integer totalSize,Integer maxSheetSize,HttpServletRequest request,HttpServletResponse response) throws Exception{ 78 if(totalSize==null || totalSize<=0) 79 totalSize=TOTAL_SIZE; 80 if(maxSheetSize==null || maxSheetSize<=0) 81 maxSheetSize=MAX_SHEET_SIZE; 82 if(fileName==null) 83 fileName=""; 84 List<File> files = beans2excelFile2007(listName, beans, result, filePath, fileName,totalSize,maxSheetSize); 85 DownLoadUtils.downLoadFiles(files, filePath, request, response); 86 } 87 88 /** 89 * 07、10办公版EXCEL导出,每个EXCEL组织数据 90 * @param listName 列表头名称 91 * @param beans 实体集合 92 * @param result 数字字典Map集 93 * @param filePath 服务器存放文件路径 94 * @param fileName 文件名称 95 * @param totalSize EXCEL条数量 96 * @param maxSheetSize sheet页条数量 97 * @return 文件集合 98 * @throws Exception 99 */ 100 private static <T> List<File> beans2excelFile2007(List<String> listName,List<T> beans,HashMap<String,HashMap<String,String>> result,String filePath,String fileName,Integer totalSize,Integer maxSheetSize) throws Exception{ 101 if ((listName == null) || (listName.size() == 0)) { 102 throw new Exception("listName is null when create excel document"); 103 } 104 List<File> listFile=new ArrayList<File>();//返回的文件集合 105 106 int size=beans==null?0:beans.size(); 107 String fileSuffixName=".xlsx";//后缀 108 String path="";//文件路径 109 Integer startIdx=0;//数据读取的起始行 110 Integer endIdx=0;//数据读取的结束行 111 (new File(filePath)).mkdirs(); //没有该目录创建目录 112 if(size==0){ 113 startIdx=0; 114 endIdx=(totalSize)>size?size:(totalSize); 115 String name=fileName+"_第0-0条数据"; 116 path=filePath+File.separatorChar+name+fileSuffixName; 117 Workbook wb =new SXSSFWorkbook(); 118 buildExcelDocument2007(wb, listName, beans,result,startIdx,endIdx,maxSheetSize); 119 //没有文件,创建文件 120 File file = new File(path); 121 if (!file.exists()){ 122 file.createNewFile(); 123 } 124 FileOutputStream out=new FileOutputStream(file); 125 wb.write(out); 126 out.close(); 127 return listFile; 128 } 129 for (int i = 0; i < size;i++) { 130 int remainder=i%totalSize; 131 if(size==0 || remainder==0){ 132 startIdx=i; 133 endIdx=(i+totalSize)>size?size:(i+totalSize); 134 String name=fileName+"_第"+(startIdx+1)+"-"+(endIdx)+"条数据"; 135 path=filePath+"/"+name+fileSuffixName; 136 Workbook wb =new SXSSFWorkbook(); 137 buildExcelDocument2007(wb, listName, beans,result,startIdx,endIdx,maxSheetSize); 138 //没有文件,创建文件 139 File file = new File(path); 140 if (!file.exists()){ 141 file.createNewFile(); 142 } 143 FileOutputStream out=new FileOutputStream(file); 144 wb.write(out); 145 out.close(); 146 listFile.add(file); 147 }else if((size-i)<totalSize && i>endIdx){//最后,不满一万条 148 startIdx=i; 149 endIdx=i+totalSize; 150 String name=fileName+"_第"+(startIdx+1)+"-"+(endIdx)+"条数据"; 151 path=filePath+name+"."+fileSuffixName;//没有文件,创建文件 152 Workbook wb =new SXSSFWorkbook(); 153 buildExcelDocument2007(wb, listName, beans, result,startIdx,endIdx,maxSheetSize); 154 //没有文件,创建文件 155 File file = new File(path); 156 if (!file.exists()){ 157 file.createNewFile(); 158 } 159 FileOutputStream out=new FileOutputStream(file); 160 wb.write(out); 161 out.close(); 162 listFile.add(file); 163 } 164 } 165 return listFile; 166 } 167 168 /** 169 * 07、10办公版EXCEL导出,每个EXCEL写入数据 170 * @param wb EXCEL工作薄 171 * @param listName 列表头名称 172 * @param beans 实体集合 173 * @param result 数字字典Map集 174 * @param startIdx 数据集合,开始行 175 * @param endIdx 数据集合,结束始行 176 * @param maxSheetSize SHEET页条数 177 * @throws Exception 178 */ 179 private static <T> void buildExcelDocument2007(Workbook wb, List<String> listName, List<T> beans,HashMap<String,HashMap<String,String>> result,Integer startIdx,Integer endIdx,Integer maxSheetSize) throws Exception 180 { 181 int totalSize=endIdx-startIdx;//总共条数 182 try 183 { 184 CellStyle cellStyle=POIUtils.getCellStyleFont(wb,null); 185 List titles = new ArrayList(); 186 List beanAttrNames = new ArrayList(); 187 boolean flagListExists=false; 188 List flagList=new ArrayList(); 189 List widthList=new ArrayList(); 190 HashMap<String,String> dateMap=new HashMap<String, String>(); 191 String[] header = new String[listName.size()]; 192 int rows_max = 0;//标题占多少列 193 for (int i=0;i<listName.size();i++) 194 { 195 String[] str=listName.get(i).split("&"); 196 String en_name=str[0]; 197 String zh_name=str[1]; 198 beanAttrNames.add(i,en_name); 199 titles.add(i, zh_name); 200 header[i]=zh_name; 201 if (zh_name.split("_").length > rows_max) { 202 rows_max = zh_name.split("_").length; 203 } 204 if(str.length>2){ 205 String flag=str[2]; 206 flagList.add(i,flag); 207 if(!flagListExists) 208 flagListExists=true; 209 } 210 if(str.length>3){ 211 widthList.add(str[3]); 212 } 213 if(str.length>4){ 214 dateMap.put(en_name, str[4]); 215 } 216 } 217 218 PropertyDescriptor[] props = null; 219 220 int size=endIdx-startIdx; 221 Sheet sheet=null; 222 223 //如果没有数据,导出表头 224 if(size==0){ 225 sheet=ExcelHeadUtils.getExcelHead2007(wb, header, "Sheet1"); 226 sheet.setDefaultRowHeight((short)350);//高度 227 setColumnWidth2007(widthList, sheet,beanAttrNames.size()); 228 return ; 229 } 230 int u=1;//用来创建每个sheet的行 231 int h=0;//用来标注每个sheet也得名字:多少行-多少行 232 for (int i = startIdx; i < endIdx ; i++) { 233 int remainder=h%maxSheetSize; 234 if(size==0 || i==startIdx || remainder==0){ 235 u=1; 236 int section=(h+maxSheetSize)>totalSize?totalSize:(h+maxSheetSize); 237 sheet=ExcelHeadUtils.getExcelHead2007(wb, header,"第"+(h+1)+"-"+section+"条"); 238 sheet.createFreezePane( 1, rows_max, 1, rows_max); 239 sheet.setDefaultRowHeight((short)350);//高度 240 setColumnWidth2007(widthList, sheet,beanAttrNames.size()); 241 } 242 if(props==null) 243 props=Introspector.getBeanInfo(beans.get(0).getClass()).getPropertyDescriptors(); 244 Object bean = beans.get(i); 245 Row row = sheet.createRow(u+rows_max-1); 246 u++; 247 h++; 248 for (int j = 0; j < beanAttrNames.size(); j++) { 249 String beanAttrName = (String)beanAttrNames.get(j); 250 String flag=""; 251 if(flagListExists) 252 flag=(String)flagList.get(j); 253 for (int k = 0; k < props.length; k++) { 254 String propName = props[k].getName(); 255 if (propName.equals(beanAttrName)) 256 { 257 String pattern=dateMap.get(beanAttrName); 258 Cell cell = row.createCell((short)j); 259 260 Object cellValue = callGetter(bean, props[k],pattern); 261 if("true".equalsIgnoreCase(flag)){ 262 if(result!=null){ 263 HashMap<String,String> hash=result.get(beanAttrName); 264 if(hash!=null) 265 cellValue=hash.get(cellValue); 266 } 267 } 268 if (cellValue == null) { 269 cellValue = ""; 270 } 271 setExcelCellText2007(cell, cellValue.toString(),cellStyle); 272 } 273 } 274 } 275 //每当行数达到设置的值就刷新数据到硬盘,以清理内存 276 if(i%FLUSH_ROWS==0){ 277 ((SXSSFSheet)sheet).flushRows(); 278 } 279 } 280 } catch (Exception e) { 281 throw new Exception(e); 282 } 283 } 284 285 /** 286 * 07、10办公版EXCEL导出(直接以流的方式,写到客户端,导出的EXCEL文件只有一个) 287 * @param listName 列表头名称 288 * @param beans 实体集合 289 * @param maxSheetSize SHEET页的条数 290 * @param outputStream 客户端输出流 291 * @throws Exception 292 */ 293 public static <T> void beans2excelFile07(List<String> listName,List<T> beans, OutputStream outputStream) throws Exception{ 294 if ((listName == null) || (listName.size() == 0)) { 295 throw new Exception("listName is null when create excel document"); 296 } 297 if (outputStream == null) { 298 throw new Exception("outputStream is null when create excel document"); 299 } 300 Workbook wb =new SXSSFWorkbook(); 301 beans2excelFile07(listName, beans, null, null, MAX_SHEET_SIZE, outputStream); 302 try { 303 wb.write(outputStream); 304 outputStream.close(); 305 } catch (IOException e) { 306 throw new Exception(e); 307 } 308 } 309 /** 310 * 07、10办公版EXCEL导出(直接以流的方式,写到客户端,导出的EXCEL文件只有一个) 311 * @param listName 列表头名称 312 * @param beans 实体集合 313 * @param maxSheetSize SHEET页的条数 314 * @param outputStream 客户端输出流 315 * @throws Exception 316 */ 317 public static <T> void beans2excelFile07(List<String> listName,List<T> beans,HashMap<String,HashMap<String,String>> result,String sheetName,Integer maxSheetSize, OutputStream outputStream) throws Exception{ 318 if ((listName == null) || (listName.size() == 0)) { 319 throw new Exception("listName is null when create excel document"); 320 } 321 if (outputStream == null) { 322 throw new Exception("outputStream is null when create excel document"); 323 } 324 if(maxSheetSize==null || maxSheetSize<=0){ 325 maxSheetSize=MAX_SHEET_SIZE; 326 } 327 if(sheetName==null || "".equals(sheetName.trim())){ 328 sheetName="Sheet"; 329 } 330 Workbook wb =new SXSSFWorkbook(); 331 if(maxSheetSize==null || maxSheetSize<=0){ 332 maxSheetSize=MAX_SHEET_SIZE; 333 } 334 buildExcelDocument2007(wb, listName, beans,result,sheetName,maxSheetSize); 335 try { 336 wb.write(outputStream); 337 outputStream.close(); 338 } catch (IOException e) { 339 throw new Exception(e); 340 } 341 } 342 /** 343 * 344 * @param listName 345 * @param beans 346 * @param response 347 * @param fileName 导出的文件名称 348 * @throws Exception 349 */ 350 public static <T> void beans2excelFile07(List<String> listName, List<T> beans, HttpServletResponse response,String fileName) throws Exception { 351 response.reset(); 352 response.setContentType("octets/stream"); 353 response.setHeader("Content-Disposition", "attachment;filename="+java.net.URLEncoder.encode(fileName, "UTF-8")); 354 if ((listName == null) || (listName.size() == 0)) { 355 throw new Exception("listName is null when create excel document"); 356 } 357 if (response.getOutputStream() == null) { 358 throw new Exception("outputStream is null when create excel document"); 359 } 360 beans2excelFile07(listName, beans, null, null, MAX_SHEET_SIZE, response.getOutputStream()); 361 } 362 /** 363 * 07、10办公版EXCEL导出,EXCEL写入数据 364 * @param wb EXCEL工作薄 365 * @param listName 列表头名称 366 * @param beans 实体集合 367 * @param maxSheetSize SHEET页的条数 368 * @throws Exception 369 */ 370 private static <T> void buildExcelDocument2007(Workbook wb, List<String> listName, List<T> beans,HashMap<String,HashMap<String,String>> result,String sheetName,Integer maxSheetSize) throws Exception 371 { 372 try 373 { 374 CellStyle cellStyle=POIUtils.getCellStyleFont(wb,null); 375 List titles = new ArrayList(); 376 List beanAttrNames = new ArrayList(); 377 List widthList = new ArrayList(); 378 HashMap<String,String> dateMap=new HashMap<String, String>(); 379 String[] header = new String[listName.size()]; 380 int rows_max = 0;//标题占多少列 381 List flagList=new ArrayList(); 382 boolean flagListExists=false; 383 for (int i=0;i<listName.size();i++) 384 { 385 String[] str=listName.get(i).split("&"); 386 String en_name=str[0]; 387 String zh_name=str[1]; 388 beanAttrNames.add(i,en_name); 389 titles.add(i, zh_name); 390 header[i]=zh_name; 391 if (zh_name.split("_").length > rows_max) { 392 rows_max = zh_name.split("_").length; 393 } 394 if(str.length>2){ 395 String flag=str[2]; 396 flagList.add(i,flag); 397 if(!flagListExists) 398 flagListExists=true; 399 } 400 if(str.length>3){ 401 widthList.add(str[3]); 402 } 403 if(str.length>4){ 404 dateMap.put(en_name, str[4]); 405 } 406 } 407 408 PropertyDescriptor[] props = null; 409 410 int size=beans==null?0:beans.size(); 411 Sheet sheet=null; 412 413 //如果没有数据,导出表头 414 if(size==0){ 415 sheet=ExcelHeadUtils.getExcelHead2007(wb, header, sheetName); 416 sheet.setDefaultRowHeight((short)350);//高度 417 setColumnWidth2007(widthList, sheet,beanAttrNames.size()); 418 return ; 419 } 420 421 for (int i = 0; i < size ; i++) { 422 int remainder=i%maxSheetSize; 423 if(size==0 || i==0 || remainder==0){ 424 sheet=ExcelHeadUtils.getExcelHead2007(wb, header,sheetName+(i/maxSheetSize)); 425 sheet.createFreezePane( 1, rows_max, 1, rows_max); 426 sheet.setDefaultRowHeight((short)350);//高度 427 setColumnWidth2007(widthList, sheet,beanAttrNames.size()); 428 } 429 if(props==null) 430 props=Introspector.getBeanInfo(beans.get(0).getClass()).getPropertyDescriptors(); 431 Object bean = beans.get(i); 432 Row row = sheet.createRow(remainder+rows_max); 433 for (int j = 0; j < beanAttrNames.size(); j++) { 434 String beanAttrName = (String)beanAttrNames.get(j); 435 String flag=""; 436 if(flagListExists) 437 flag=(String)flagList.get(j); 438 for (int k = 0; k < props.length; k++) { 439 String propName = props[k].getName(); 440 if (propName.equals(beanAttrName)) 441 { 442 String pattern=dateMap.get(beanAttrName); 443 Cell cell = row.createCell((short)j); 444 445 Object cellValue = callGetter(bean, props[k],pattern); 446 if("true".equalsIgnoreCase(flag)){ 447 if(result!=null){ 448 HashMap<String,String> hash=result.get(beanAttrName); 449 if(hash!=null) 450 cellValue=hash.get(cellValue); 451 } 452 } 453 if (cellValue == null) { 454 cellValue = ""; 455 } 456 setExcelCellText2007(cell, cellValue.toString(),cellStyle); 457 } 458 } 459 } 460 //每当行数达到设置的值就刷新数据到硬盘,以清理内存 461 if(i%FLUSH_ROWS==0){ 462 ((SXSSFSheet)sheet).flushRows(); 463 } 464 } 465 } catch (Exception e) { 466 throw new Exception(e); 467 } 468 } 469 /** 470 * 07、10办公版EXCEL导出(直接以流的方式,写到客户端,导出的EXCEL文件只有一个) 471 * @param listName 列表头名称 472 * @param beans 实体集合 473 * @param maxSheetSize SHEET页的条数 474 * @param outputStream 客户端输出流 475 * @throws Exception 476 */ 477 public static <T> void beans2excelFile07List(List<ArrayList<String>> listColumnName,List<List> list2beans,HashMap<String,HashMap<String,HashMap<String,String>>> result,List<String> listSheetName, OutputStream outputStream) throws Exception{ 478 if ((listColumnName == null) || (listColumnName.size() == 0)) { 479 throw new Exception("listColumnName is null when create excel document"); 480 } 481 if (list2beans.size() != listColumnName.size()) { 482 throw new Exception("list2beans and listColumnName size Unequal"); 483 } 484 if (outputStream == null) { 485 throw new Exception("outputStream is null when create excel document"); 486 } 487 Workbook wb =new SXSSFWorkbook(); 488 buildExcelDocument2007List(wb, listColumnName, list2beans, result, listSheetName); 489 try { 490 wb.write(outputStream); 491 outputStream.close(); 492 } catch (IOException e) { 493 throw new Exception(e); 494 } 495 } 496 /** 497 * 07、10办公版EXCEL导出,EXCEL写入数据 498 * @param wb EXCEL工作薄 499 * @param listName 列表头名称 500 * @param beans 实体集合 501 * @param maxSheetSize SHEET页的条数 502 * @throws Exception 503 */ 504 private static <T> void buildExcelDocument2007List(Workbook wb, List<ArrayList<String>> listColumnName,List<List> list2beans,HashMap<String,HashMap<String,HashMap<String,String>>> resultMap,List<String> listSheetName) throws Exception 505 { 506 try 507 { 508 int sheets=listColumnName.size(); 509 boolean sheetNameIsNullFlag=false; 510 if(listSheetName==null || listSheetName.size()!=sheets){ 511 sheetNameIsNullFlag=true; 512 } 513 for (int s = 0; s < sheets; s++) { 514 String sheetName="Sheet"+s; 515 if(!sheetNameIsNullFlag){ 516 sheetName=listSheetName.get(s); 517 } 518 List<String> listName=listColumnName.get(s); 519 CellStyle cellStyle=POIUtils.getCellStyleFont(wb,null); 520 List titles = new ArrayList(); 521 List beanAttrNames = new ArrayList(); 522 List widthList = new ArrayList(); 523 HashMap<String,String> dateMap=new HashMap<String, String>(); 524 String[] header = new String[listName.size()]; 525 int rows_max = 0;//标题占多少列 526 List flagList=new ArrayList(); 527 boolean flagListExists=false; 528 for (int i=0;i<listName.size();i++) 529 { 530 String[] str=listName.get(i).split("&"); 531 String en_name=str[0]; 532 String zh_name=str[1]; 533 beanAttrNames.add(i,en_name); 534 titles.add(i, zh_name); 535 header[i]=zh_name; 536 if (zh_name.split("_").length > rows_max) { 537 rows_max = zh_name.split("_").length; 538 } 539 if(str.length>2){ 540 String flag=str[2]; 541 flagList.add(i,flag); 542 if(!flagListExists) 543 flagListExists=true; 544 } 545 if(str.length>3){ 546 widthList.add(str[3]); 547 } 548 if(str.length>4){ 549 dateMap.put(en_name, str[4]); 550 } 551 } 552 553 PropertyDescriptor[] props = null; 554 ArrayList<T> beans=(ArrayList<T>)list2beans.get(s); 555 int size=beans==null?0:beans.size(); 556 Sheet sheet=null; 557 558 //如果没有数据,导出表头 559 if(size==0){ 560 sheet=ExcelHeadUtils.getExcelHead2007(wb, header, sheetName); 561 sheet.setDefaultRowHeight((short)350);//高度 562 setColumnWidth2007(widthList, sheet,beanAttrNames.size()); 563 return ; 564 } 565 566 HashMap<String,HashMap<String,String>> result=null; 567 if(resultMap!=null){ 568 result=resultMap.get(sheetName); 569 } 570 sheet=ExcelHeadUtils.getExcelHead2007(wb, header,sheetName); 571 sheet.createFreezePane( 1, rows_max, 1, rows_max); 572 sheet.setDefaultRowHeight((short)350);//高度 573 setColumnWidth2007(widthList, sheet,beanAttrNames.size()); 574 for (int i = 0; i < size ; i++) { 575 if(props==null) 576 props=Introspector.getBeanInfo(beans.get(0).getClass()).getPropertyDescriptors(); 577 Object bean = beans.get(i); 578 Row row = sheet.createRow(rows_max+i); 579 for (int j = 0; j < beanAttrNames.size(); j++) { 580 String beanAttrName = (String)beanAttrNames.get(j); 581 String flag=""; 582 if(flagListExists) 583 flag=(String)flagList.get(j); 584 for (int k = 0; k < props.length; k++) { 585 String propName = props[k].getName(); 586 if (propName.equals(beanAttrName)) 587 { 588 String pattern=dateMap.get(beanAttrName); 589 Cell cell = row.createCell((short)j); 590 591 Object cellValue = callGetter(bean, props[k],pattern); 592 if("true".equalsIgnoreCase(flag)){ 593 if(result!=null){ 594 HashMap<String,String> hash=result.get(beanAttrName); 595 if(hash!=null) 596 cellValue=hash.get(cellValue); 597 } 598 } 599 if (cellValue == null) { 600 cellValue = ""; 601 } 602 setExcelCellText2007(cell, cellValue.toString(),cellStyle); 603 } 604 } 605 } 606 //每当行数达到设置的值就刷新数据到硬盘,以清理内存 607 if(i%FLUSH_ROWS==0){ 608 ((SXSSFSheet)sheet).flushRows(); 609 } 610 } 611 } 612 } catch (Exception e) { 613 throw new Exception(e); 614 } 615 } 616 /** 617 * 07、10办公版EXCEL导出,单元格设置 618 * @param cell 单元格对象 619 * @param text 单元格文本内容 620 * @param cellStyle 单元格格式 621 */ 622 private static void setExcelCellText2007(Cell cell, Object text,CellStyle cellStyle) 623 { 624 cell.setCellValue(text.toString()); 625 cell.setCellType(1);//单元格类型 626 cell.setCellStyle(cellStyle); 627 } 628 629 /** 630 * 07、10办公版EXCEL导出,单元格宽度设置 631 * @param widthList 列宽集合 632 * @param sheet sheet对象 633 * @param allSize 总列数 634 */ 635 private static void setColumnWidth2007(List widthList,Sheet sheet,int allSize){ 636 if(widthList!=null && widthList.size()>0){ 637 int size=widthList.size(); 638 for (int i = 0; i < size; i++) { 639 try { 640 Integer width=Integer.parseInt((String) widthList.get(i)); 641 sheet.setColumnWidth((short) i,width*256); 642 } catch (NumberFormatException e) { 643 continue; 644 } 645 } 646 }else{ 647 for (int i = 0; i < allSize; i++) { 648 try { 649 sheet.setColumnWidth((short) i,COLUMN_WIDTH_WORD*256); 650 } catch (NumberFormatException e) { 651 continue; 652 } 653 } 654 655 } 656 } 657 658 /** 659 * 03、WPS:EXCEL导出(数据直接写到服务器的EXCEL里,以下载的形式,下载导出的数据) 660 * @param listName 列表头名称 661 * @param beans 实体集合 662 * @param result 数字字典Map集 663 * @param filePath 服务器存放文件路径 664 * @param fileName 文件名称 665 * @param totalSize EXCEL条数量 666 * @param maxSheetSize sheet页条数量 667 * @return List<File> 文件集合 668 * @throws Exception 669 */ 670 public static <T> List<File> beans2excelFile03(List<String> listName,List<T> beans,HashMap<String,HashMap<String,String>> result,String filePath,String fileName,Integer totalSize,Integer maxSheetSize) throws Exception{ 671 if(totalSize==null || totalSize<=0) 672 totalSize=TOTAL_SIZE; 673 if(maxSheetSize==null || maxSheetSize<=0) 674 maxSheetSize=MAX_SHEET_SIZE; 675 if(fileName==null) 676 fileName=""; 677 return beans2excelFile2003(listName, beans, result, filePath, fileName,totalSize,maxSheetSize); 678 } 679 /** 680 * 03、WPS:EXCEL导出(数据直接写到服务器的EXCEL里,以下载的形式,下载导出的数据) 681 * @param listName 列表头名称 682 * @param beans 实体集合 683 * @param result 数字字典Map集 684 * @param filePath 服务器存放文件路径 685 * @param fileName 文件名称 686 * @param totalSize EXCEL条数量 687 * @param maxSheetSize sheet页条数量 688 * @param request 客户端请求对象 689 * @param response 客户端响应对象 690 * @throws Exception 691 */ 692 public static <T> void beans2excelFile03(List<String> listName,List<T> beans,HashMap<String,HashMap<String,String>> result,String filePath,String fileName,Integer totalSize,Integer maxSheetSize,HttpServletRequest request,HttpServletResponse response) throws Exception{ 693 if(totalSize==null || totalSize<=0) 694 totalSize=TOTAL_SIZE; 695 if(maxSheetSize==null || maxSheetSize<=0) 696 maxSheetSize=MAX_SHEET_SIZE; 697 if(fileName==null) 698 fileName=""; 699 List<File> files=beans2excelFile2003(listName, beans, result, filePath, fileName,totalSize,maxSheetSize); 700 DownLoadUtils.downLoadFiles(files, filePath, request, response); 701 } 702 /** 703 * 03、WPS:EXCEL导出,每个EXCEL组织数据 704 * @param listName 列表头名称 705 * @param beans 实体集合 706 * @param result 数字字典Map集 707 * @param filePath 服务器存放文件路径 708 * @param fileName 文件名称 709 * @param totalSize EXCEL条数量 710 * @param maxSheetSize sheet页条数量 711 * @return 文件集合 712 * @throws Exception 713 */ 714 private static <T> List<File> beans2excelFile2003(List<String> listName,List<T> beans,HashMap<String,HashMap<String,String>> result,String filePath,String fileName,Integer totalSize,Integer maxSheetSize) throws Exception{ 715 if ((listName == null) || (listName.size() == 0)) { 716 throw new Exception("listName is null when create excel document"); 717 } 718 List<File> listFile=new ArrayList<File>();//返回的文件集合 719 720 int size=beans==null?0:beans.size(); 721 String fileSuffixName=".xls";//后缀 722 String path="";//文件路径 723 Integer startIdx=0;//数据读取的起始行 724 Integer endIdx=0;//数据读取的结束行 725 (new File(filePath)).mkdirs(); //没有该目录创建目录 726 if(size==0){ 727 startIdx=0; 728 endIdx=(totalSize)>size?size:(totalSize); 729 String name=fileName+"_第0-0条数据"; 730 path=filePath+File.separatorChar+name+fileSuffixName; 731 HSSFWorkbook wb =new HSSFWorkbook(); 732 buildExcelDocument2003(wb, listName, beans,result,startIdx,endIdx,maxSheetSize); 733 //没有文件,创建文件 734 File file = new File(path); 735 if (!file.exists()){ 736 file.createNewFile(); 737 } 738 FileOutputStream out=new FileOutputStream(file); 739 wb.write(out); 740 out.close(); 741 return listFile; 742 } 743 for (int i = 0; i < size;i++) { 744 int remainder=i%totalSize; 745 if(size==0 || remainder==0){ 746 startIdx=i; 747 endIdx=(i+totalSize)>size?size:(i+totalSize); 748 String name=fileName+"_第"+(startIdx+1)+"-"+(endIdx)+"条数据"; 749 path=filePath+"/"+name+fileSuffixName; 750 HSSFWorkbook wb =new HSSFWorkbook(); 751 buildExcelDocument2003(wb, listName, beans,result,startIdx,endIdx,maxSheetSize); 752 //没有文件,创建文件 753 File file = new File(path); 754 if (!file.exists()){ 755 file.createNewFile(); 756 } 757 FileOutputStream out=new FileOutputStream(file); 758 wb.write(out); 759 out.close(); 760 listFile.add(file); 761 }else if((size-i)<totalSize && i>endIdx){//最后,不满一万条 762 startIdx=i; 763 endIdx=i+totalSize; 764 String name=fileName+"_第"+(startIdx+1)+"-"+(endIdx)+"条数据"; 765 path=filePath+name+"."+fileSuffixName;//没有文件,创建文件 766 HSSFWorkbook wb =new HSSFWorkbook(); 767 buildExcelDocument2003(wb, listName, beans, result,startIdx,endIdx,maxSheetSize); 768 //没有文件,创建文件 769 File file = new File(path); 770 if (!file.exists()){ 771 file.createNewFile(); 772 } 773 FileOutputStream out=new FileOutputStream(file); 774 wb.write(out); 775 out.close(); 776 listFile.add(file); 777 } 778 } 779 return listFile; 780 } 781 782 /** 783 * 03,WPS:EXCEL导出,每个EXCEL写入数据 784 * @param wb EXCEL工作薄 785 * @param listName 列表头名称 786 * @param beans 实体集合 787 * @param result 数字字典Map集 788 * @param startIdx 数据集合,开始行 789 * @param endIdx 数据集合,结束始行 790 * @param maxSheetSize SHEET页条数 791 * @throws Exception 792 */ 793 private static <T> void buildExcelDocument2003(HSSFWorkbook wb, List<String> listName, List<T> beans,HashMap<String,HashMap<String,String>> result,Integer startIdx,Integer endIdx,Integer maxSheetSize) throws Exception 794 { 795 int totalSize=endIdx-startIdx;//总共条数 796 try 797 { 798 CellStyle cellStyle=POIUtils.getCellStyleFont(wb,null); 799 List titles = new ArrayList(); 800 List beanAttrNames = new ArrayList(); 801 List widthList=new ArrayList(); 802 String[] header = new String[listName.size()]; 803 List flagList=new ArrayList(); 804 boolean flagListExists=false; 805 int rows_max = 0;//标题占多少列 806 HashMap<String,String> dateMap=new HashMap<String, String>(); 807 for (int i=0;i<listName.size();i++) 808 { 809 String[] str=listName.get(i).split("&"); 810 String en_name=str[0]; 811 String zh_name=str[1]; 812 beanAttrNames.add(i,en_name); 813 titles.add(i, zh_name); 814 header[i]=zh_name; 815 if (zh_name.split("_").length > rows_max) { 816 rows_max = zh_name.split("_").length; 817 } 818 if(str.length>2){ 819 String flag=str[2]; 820 flagList.add(i,flag); 821 if(!flagListExists) 822 flagListExists=true; 823 } 824 if(str.length>3){ 825 widthList.add(str[3]); 826 } 827 if(str.length>4){ 828 dateMap.put(en_name, str[4]); 829 } 830 } 831 832 PropertyDescriptor[] props = null; 833 834 int size=endIdx-startIdx; 835 HSSFSheet sheet=null; 836 837 //如果没有数据,导出表头 838 if(size==0){ 839 sheet=ExcelHeadUtils.getExcelHead2003(wb, header, "Sheet1"); 840 sheet.setDefaultRowHeight((short)350);//高度 841 setColumnWidth2003(widthList, sheet,beanAttrNames.size()); 842 return ; 843 } 844 int u=1;//用来创建每个sheet的行 845 int h=0;//用来标注每个sheet也得名字:多少行-多少行 846 for (int i = startIdx; i < endIdx ; i++) { 847 int remainder=h%maxSheetSize; 848 if(size==0 || i==startIdx || remainder==0){ 849 u=1; 850 int section=(h+maxSheetSize)>totalSize?totalSize:(h+maxSheetSize); 851 sheet=ExcelHeadUtils.getExcelHead2003(wb, header, "第"+(h+1)+"-"+section+"条"); 852 sheet.createFreezePane( 1, rows_max, 1, rows_max); 853 sheet.setDefaultRowHeight((short)350);//高度 854 setColumnWidth2003(widthList, sheet,beanAttrNames.size()); 855 } 856 if(props==null) 857 props=Introspector.getBeanInfo(beans.get(0).getClass()).getPropertyDescriptors(); 858 Object bean = beans.get(i); 859 HSSFRow row = sheet.createRow(u+rows_max-1); 860 u++; 861 h++; 862 for (int j = 0; j < beanAttrNames.size(); j++) { 863 String beanAttrName = (String)beanAttrNames.get(j); 864 String flag=null; 865 if(flagListExists) 866 flag=(String)flagList.get(j); 867 for (int k = 0; k < props.length; k++) { 868 String propName = props[k].getName(); 869 if (propName.equals(beanAttrName)) 870 { 871 String pattern=dateMap.get(beanAttrName); 872 HSSFCell cell = row.createCell((short)j); 873 Object cellValue = callGetter(bean, props[k],pattern); 874 if("true".equalsIgnoreCase(flag)){ 875 if(result!=null){ 876 HashMap<String,String> hash=result.get(beanAttrName); 877 if(hash!=null) 878 cellValue=hash.get(cellValue); 879 } 880 } 881 if (cellValue == null) { 882 cellValue = ""; 883 } 884 setExcelCellText2003(cell, cellValue.toString(),cellStyle); 885 } 886 } 887 } 888 } 889 } catch (Exception e) { 890 throw new Exception(e); 891 } 892 } 893 894 /** 895 * 03,WPS:EXCEL导出(直接以流的方式,写到客户端,导出的EXCEL文件只有一个) 896 * @param listName 列表头名称 897 * @param beans 实体集合 898 * @param maxSheetSize sheet页条数量 899 * @param outputStream 客户端输出流 900 * @throws Exception 901 */ 902 public static <T> void beans2excelFile03(List<String> listName,List<T> beans,HashMap<String,HashMap<String,String>> result,String sheetName,Integer maxSheetSize, OutputStream outputStream) throws Exception{ 903 if ((listName == null) || (listName.size() == 0)) { 904 throw new Exception("listName is null when create excel document"); 905 } 906 if(maxSheetSize==null || maxSheetSize<=0){ 907 maxSheetSize=MAX_SHEET_SIZE; 908 } 909 if(sheetName==null || "".equals(sheetName.trim())){ 910 sheetName="Sheet"; 911 } 912 HSSFWorkbook wb =new HSSFWorkbook(); 913 if(maxSheetSize==null || maxSheetSize<=0) 914 maxSheetSize=MAX_SHEET_SIZE; 915 buildExcelDocument2003(wb, listName, beans,result,sheetName,maxSheetSize); 916 try { 917 wb.write(outputStream); 918 outputStream.close(); 919 } catch (IOException e) { 920 throw new Exception(e); 921 } 922 } 923 924 /** 925 * 03,WPS:EXCEL导出,EXCEL写入数据 926 * @param wb EXCEL工作薄 927 * @param listName 列表头名称 928 * @param beans 实体集合 929 * @param maxSheetSize sheet页条数量 930 * @throws Exception 931 */ 932 private static <T> void buildExcelDocument2003(HSSFWorkbook wb, List<String> listName, List<T> beans,HashMap<String,HashMap<String,String>> result,String sheetName,Integer maxSheetSize) throws Exception 933 { 934 try 935 { 936 CellStyle cellStyle=POIUtils.getCellStyleFont(wb,null); 937 List titles = new ArrayList(); 938 List beanAttrNames = new ArrayList(); 939 List widthList = new ArrayList(); 940 HashMap<String,String> dateMap=new HashMap<String, String>(); 941 String[] header = new String[listName.size()]; 942 int rows_max = 0;//标题占多少列 943 List flagList=new ArrayList(); 944 boolean flagListExists=false; 945 for (int i=0;i<listName.size();i++) 946 { 947 String[] str=listName.get(i).split("&"); 948 String en_name=str[0]; 949 String zh_name=str[1]; 950 beanAttrNames.add(i,en_name); 951 titles.add(i, zh_name); 952 header[i]=zh_name; 953 if (zh_name.split("_").length > rows_max) { 954 rows_max = zh_name.split("_").length; 955 } 956 if(str.length>2){ 957 String flag=str[2]; 958 flagList.add(i,flag); 959 if(!flagListExists) 960 flagListExists=true; 961 } 962 if(str.length>3){ 963 widthList.add(str[3]); 964 } 965 if(str.length>4){ 966 dateMap.put(en_name, str[4]); 967 } 968 } 969 PropertyDescriptor[] props =null; 970 971 int size=beans==null?0:beans.size(); 972 HSSFSheet sheet=null; 973 //如果没有数据,导出表头 974 if(size==0){ 975 sheet=ExcelHeadUtils.getExcelHead2003(wb, header, sheetName); 976 setColumnWidth2003(widthList, sheet,beanAttrNames.size()); 977 sheet.setDefaultRowHeight((short)350);//高度 978 return ; 979 } 980 for (int i = 0; i < size ; i++) { 981 int remainder=i%maxSheetSize; 982 if(size==0 || i==0 || remainder==0){ 983 sheet=ExcelHeadUtils.getExcelHead2003(wb, header, sheetName+(i/maxSheetSize)); 984 sheet.createFreezePane( 1, rows_max, 1, rows_max); 985 setColumnWidth2003(widthList, sheet,beanAttrNames.size()); 986 sheet.setDefaultRowHeight((short)350);//高度 987 } 988 if(props==null) 989 props= Introspector.getBeanInfo(beans.get(0).getClass()).getPropertyDescriptors(); 990 Object bean = beans.get(i); 991 HSSFRow row = sheet.createRow(remainder+rows_max); 992 for (int j = 0; j < beanAttrNames.size(); j++) { 993 994 String beanAttrName = (String)beanAttrNames.get(j); 995 String flag=null; 996 if(flagListExists) 997 flag=(String)flagList.get(j); 998 for (int k = 0; k < props.length; k++) { 999 String propName = props[k].getName(); 1000 if (propName.equals(beanAttrName)) 1001 { 1002 String pattern=dateMap.get(beanAttrName); 1003 HSSFCell cell = row.createCell((short)j); 1004 Object cellValue = callGetter(bean, props[k],pattern); 1005 if("true".equalsIgnoreCase(flag)){ 1006 if(result!=null){ 1007 HashMap<String,String> hash=result.get(beanAttrName); 1008 if(hash!=null) 1009 cellValue=hash.get(cellValue); 1010 } 1011 } 1012 if (cellValue == null) { 1013 cellValue = ""; 1014 } 1015 setExcelCellText2003(cell, cellValue.toString(),cellStyle); 1016 } 1017 } 1018 } 1019 } 1020 } catch (Exception e) { 1021 throw new Exception(e); 1022 } 1023 } 1024 1025 /** 1026 * 03,WPS:EXCEL导出,单元格设置 1027 * @param cell 单元格对象 1028 * @param text 单元格文本内容 1029 * @param cellStyle 单元格格式 1030 */ 1031 private static void setExcelCellText2003(HSSFCell cell, Object text,CellStyle cellStyle) 1032 { 1033 cell.setCellValue(text.toString()); 1034 cell.setCellType(1);//单元格类型 1035 cell.setCellStyle(cellStyle); 1036 } 1037 1038 /** 1039 * 03,WPS:EXCEL导出,单元格宽度设置 1040 * @param widthList 列宽集合 1041 * @param sheet sheet对象 1042 * @param allSize 总列数 1043 */ 1044 private static void setColumnWidth2003(List widthList,HSSFSheet sheet,int allSize){ 1045 if(widthList!=null && widthList.size()>0){ 1046 int size=widthList.size(); 1047 for (int i = 0; i < size; i++) { 1048 try { 1049 Integer width=Integer.parseInt((String) widthList.get(i)); 1050 sheet.setColumnWidth((short) i,width*256); 1051 } catch (NumberFormatException e) { 1052 continue; 1053 } 1054 } 1055 }else{ 1056 for (int i = 0; i < allSize; i++) { 1057 try { 1058 sheet.setColumnWidth((short) i,COLUMN_WIDTH_WORD*256); 1059 } catch (NumberFormatException e) { 1060 continue; 1061 } 1062 } 1063 } 1064 } 1065 1066 /** 1067 * 根据反射,获取实体属性的值 1068 * @param target 实体属性 1069 * @param prop 反射调用类 1070 * @param pattern 日期格式 1071 * @return 1072 */ 1073 private static Object callGetter(Object target, PropertyDescriptor prop,String pattern) { 1074 Object o = null; 1075 if (prop.getReadMethod() != null) { 1076 try { 1077 o = prop.getReadMethod().invoke(target, null); 1078 if (Date.class.equals(prop.getPropertyType())) { 1079 if(pattern!=null && !"".equals(pattern)){ 1080 try { 1081 o = new SimpleDateFormat(pattern).format(o); 1082 } catch (Exception e) { 1083 o = new SimpleDateFormat(PATTERN).format(o); 1084 } 1085 }else{ 1086 o = formatDate(o); 1087 } 1088 } 1089 } catch (Exception e) { 1090 o = null; 1091 } 1092 } 1093 return o; 1094 } 1095 1096 /** 1097 * 日期转换 1098 * @param date 1099 * @return 字符串的日期 1100 */ 1101 private static String formatDate(Object date) { 1102 if(date==null) 1103 return ""; 1104 String dateStr = new SimpleDateFormat(DATE_HH_PATTERN).format(date); 1105 if("00:00:00".equals(dateStr)){ 1106 return new SimpleDateFormat(DATE_PATTERN).format(date); 1107 } 1108 return new SimpleDateFormat(PATTERN).format(date); 1109 } 1110}

然后看看效果吧:

点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

MySQL部分从库上面因为大量的临时表tmp_table造成慢查询

背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_

皕杰报表之UUID

​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

2020年前端实用代码段,为你的工作保驾护航

有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )