Hutool Java 工具類庫導(dǎo)出 Excel,超級簡單!
點擊上方“藍(lán)色字體”,選擇“設(shè)為星標(biāo)”
做積極的人,而不是積極廢人!
來源:toutiao.com/i6771298852050829835
前言
在開發(fā)應(yīng)用系統(tǒng)的時候,導(dǎo)出文件是必不可放的功能。
以前用過POI、easyexcel等工具的導(dǎo)入導(dǎo)出功能,但總感覺太麻煩了,代碼特別多,感覺并不是很好用。
今天給大家介紹一款新工具,java工具類庫Hutool。
Hutool簡介
Hutool是一個小而全的Java工具類庫,通過靜態(tài)方法封裝,降低相關(guān)API的學(xué)習(xí)成本,提高工作效率,使Java擁有函數(shù)式語言般的優(yōu)雅,讓使用者更輕松。
Hutool中的工具方法來自于每個用戶的精雕細(xì)琢,它涵蓋了Java開發(fā)底層代碼中的方方面面,它既是大型項目開發(fā)中解決小問題的利器,也是小型項目中的效率擔(dān)當(dāng);
Hutool是項目中“util”包友好的替代,它節(jié)省了開發(fā)人員對項目中公用類和公用工具方法的封裝時間,使開發(fā)專注于業(yè)務(wù),同時可以最大限度的避免封裝不完善帶來的bug。
使用
首先在POM.xml中加入GAV
<dependency>
????<groupId>cn.hutoolgroupId>
????<artifactId>hutool-allartifactId>
????<version>5.0.7version>
dependency>
<dependency>
????<groupId>org.apache.poigroupId>
????<artifactId>poi-ooxmlartifactId>
????<version>4.1.1version>
dependency>
<dependency>
????<groupId>org.apache.poigroupId>
????<artifactId>poi-ooxml-schemasartifactId>
????<version>3.17version>
dependency>
然后在控制層使用就行
@RequestMapping("/export")
@ResponseBody
public?void?export(HttpServletResponse?response){
?List?list?=?new?ArrayList<>();
?list.add(new?User("zhangsan","1231",new?Date()));
?list.add(new?User("zhangsan1","1232",new?Date()));
?list.add(new?User("zhangsan2","1233",new?Date()));
?list.add(new?User("zhangsan3","1234",new?Date()));
?list.add(new?User("zhangsan4","1235",new?Date()));
?list.add(new?User("zhangsan5","1236",?DateUtil.date(new?Date())));
?//?通過工具類創(chuàng)建writer,默認(rèn)創(chuàng)建xls格式
?ExcelWriter?writer?=?ExcelUtil.getWriter();
?//自定義標(biāo)題別名
?writer.addHeaderAlias("name",?"姓名");
?writer.addHeaderAlias("age",?"年齡");
?writer.addHeaderAlias("birthDay",?"生日");
?//?合并單元格后的標(biāo)題行,使用默認(rèn)標(biāo)題樣式
?writer.merge(2,?"申請人員信息");
?//?一次性寫出內(nèi)容,使用默認(rèn)樣式,強制輸出標(biāo)題
?writer.write(list,?true);
?//out為OutputStream,需要寫出到的目標(biāo)流
?//response為HttpServletResponse對象
?response.setContentType("application/vnd.ms-excel;charset=utf-8");
?//test.xls是彈出下載對話框的文件名,不能為中文,中文請自行編碼
?String?name?=?StringUtils.toUtf8String("申請學(xué)院");
?response.setHeader("Content-Disposition","attachment;filename="+name+".xls");
?ServletOutputStream?out=?null;
?try?{
??out?=?response.getOutputStream();
??writer.flush(out,?true);
?}
?catch?(IOException?e)?{
??e.printStackTrace();
?}
?finally?{
??//?關(guān)閉writer,釋放內(nèi)存
??writer.close();
?}
?//此處記得關(guān)閉輸出Servlet流
?IoUtil.close(out);
}
效果
看到這里就已經(jīng)結(jié)束了,是不是很簡單?
-?end?-
用心分享面試知識,做有溫度的攻城獅
每天記得對自己說:你是最棒的!
往期推薦:
每一個“好看”,都是對我們最大的幫助
評論
圖片
表情

