SSM MySql資料匯出到Excel
阿新 • • 發佈:2019-05-23
語言:java
框架:SSM
工程:maven
工具類:ExcelUtils.java
工具類下載地址:https://download.csdn.net/download/ledzcl/10234291
備註:本下載地址來源CSDN的dedzcl的部落格(連線:https://blog.csdn.net/ledzcl/article/details/79222737)
僅此備忘
1、工具類下載完成後直接放到maven工程裡,我放到了util包下
2、pom中新增jar包依賴關係
<!-- 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/poi
3、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