前言
在开发应用系统的时候,导出文件是必不可放的功能。
以前用过POI、easyexcel等工具的导入导出功能,但总感觉太麻烦了,代码特别多,感觉并不是很好用。
今天给大家介绍一款新工具,java工具类库Hutool。之前整体介绍过该工具库:贼好用的Java工具类库,GitHub星标10k+,你在用吗?
Hutool简介
Hutool是一个小而全的Java工具类库,通过静态方法封装,降低相关API的学习成本,提高工作效率,使Java拥有函数式语言般的优雅,让使用者更轻松。
Hutool中的工具方法来自于每个用户的精雕细琢,它涵盖了Java开发底层代码中的方方面面,它既是大型项目开发中解决小问题的利器,也是小型项目中的效率担当;
Hutool是项目中“util”包友好的替代,它节省了开发人员对项目中公用类和公用工具方法的封装时间,使开发专注于业务,同时可以最大限度的避免封装不完善带来的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() ) ) );
/* 通过工具类创建writer,默认创建xls格式 */
ExcelWriter writer = ExcelUtil.getWriter();
/* 自定义标题别名 */
writer.addHeaderAlias( "name", "姓名" );
writer.addHeaderAlias( "age", "年龄" );
writer.addHeaderAlias( "birthDay", "生日" );
/* 合并单元格后的标题行,使用默认标题样式 */
writer.merge( 2, "申请人员信息" );
/* 一次性写出内容,使用默认样式,强制输出标题 */
writer.write( list, true );
/* out为OutputStream,需要写出到的目标流 */
/* response为HttpServletResponse对象 */
response.setContentType( "application/vnd.ms-excel;charset=utf-8" );
/* test.xls是弹出下载对话框的文件名,不能为中文,中文请自行编码 */
String name = StringUtils.toUtf8String( "申请学院" );
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 {
/* 关闭writer,释放内存 */
writer.close();
}
/* 此处记得关闭输出Servlet流 */
IoUtil.close( out );
}
效果
额外资源
感谢您阅读excelxue的Excel功能指南!要了解更多信息,请查看以下其他excelxue资源: