語言:javajava
框架:SSMapache
工程:mavenapp
工具類:ExcelUtils.java框架
工具類下載地址:https://download.csdn.net/download/ledzcl/10234291maven
備註:本下載地址來源CSDN的dedzcl的博客(鏈接:https://blog.csdn.net/ledzcl/article/details/79222737)工具
僅此備忘spa
一、工具類下載完成後直接放到maven工程裏,我放到了util包下.net
二、pom中添加jar包依賴關係excel
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.9</version> </dependency>
jar包下載地址:https://mvnrepository.com/artifact/org.apache.poi/poicode
三、controller層添加requestMapper
@ResponseBody @RequestMapping("/allExcel") public void AllExcel(HttpServletResponse res) { try { ServletOutputStream out = res.getOutputStream(); res.setContentType("application/vnd.ms-excel"); res.setHeader("Content-disposition", "attachment;filename=" + new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new Date())+URLEncoder.encode("全部", "UTF-8") + ".xls"); Collection<Object[]> collection=new ArrayList<>(); // List<Mess> allList = mService.getDownloadAll(); // System.out.println(allList); for(Mess mess:allList) { Object[] os=new Object[20]; os[0]=mess.getNumber(); os[1]=mess.getSname(); os[2]=mess.getIdcard(); os[3]=mess.getSex(); os[4]=mess.getBirthdate(); os[5]=mess.getNation(); os[6]=mess.getNativeplace(); os[7]=mess.getHomeadress(); os[8]=mess.getSgs(); os[9]=mess.getSgc(); os[10]=mess.getScadre(); os[11]=mess.getDsfirst(); os[12]=mess.getDssecound(); os[13]=mess.getDsthird(); os[14]=mess.getPname(); os[15]=mess.getRelationship(); os[16]=mess.getUnit(); os[17]=mess.getDuty(); os[18]=mess.getPhonenumber(); os[19]=mess.getPaiwei(); collection.add(os); } // String[] columnNames=new String[] { "編號","姓名","身份證號","性別","出身日期","民族","戶口所在地","家庭住址","畢業學校","畢業班級", "曾任課表明","第一心儀學校","第二心儀學校","第三心儀學校","家長姓名","與學生關係","單位","職務","聯繫方式","是否參加派位" }; int[] columnIndexs=new int[] {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19}; ExcelUtils.export(collection, "全部學生", columnNames, columnIndexs, 100, out); out.flush(); out.close(); }catch(Exception e) { e.printStackTrace(); } }
解釋:
(1)調用工具類中的ExcelUtils.export();便可完成Excel的生成及下載
(2)HttpServletResponse須要設置content type爲res.setContentType("application/vnd.ms-excel");
(3)防止中文亂碼URLEncoder.encode("全部", "UTF-8")
(4)Collection<Object[]>故須要把service層返回的list轉成object放入到Collection<Object[]>中
(5)columnNames和columnIndexs及Collection<Object[]>中的Object[]三者爲一一對應關係
(6)最後別忘了out.flush();和out.close();
結束...