1、Hutool工具简介
HuTool工具(糊涂工具),第三方插件工具,简化操作,是国产的一个产品,界面简洁易懂,比较人性化。(上班可能经常用的到,建议收藏起来)
Hutool是一个小而全的Java工具类库,通过静态方法封装,降低相关API的学习成本,提高工作效率,使Java拥有函数式语言般的优雅,让Java语言也可以“甜甜的”。
2、Hutool的相关依赖
maven项目在pom.xml添加以下依赖即可:
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>4.6.3</version>
</dependency>
3、验证码工具
@Test
public void hutoolCodeTest() throws FileNotFoundException {
LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 40, 4, 4);
//2.获得生成的验证码的真实码值
String code = lineCaptcha.getCode();
System.out.println(code);
//3.将验证码图片输出到D盘根目录下
lineCaptcha.write(new FileOutputStream("D:/text.png"));
}
4、excel工具
POI依赖导入,否则报错
You need to add dependency of 'poi-ooxml' to your project, and version >= 3.17
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.17</version>
</dependency>
(1)Exel导出
@Test
public void HutollDownLoadExcelTest() throws FileNotFoundException {
//1.创建一个Excel写出工具Writer
ExcelWriter writer = ExcelUtil.getWriter(true);
//2.模拟List数据
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
//3.将list数据输出到excel中
writer.write(list);
//4. 将填充数据后的excel文件保存在d盘文件中.
writer.flush(new FileOutputStream("d:/id.xlsx"));
}
(2)excel导出详细讲解
实体类
public class User {
private String id;
private String name;
private Integer age;
测试类
//1. 创建一个Excel写出工具Writer
ExcelWriter writer = ExcelUtil.getWriter(true);
//2. 设置别名
writer.addHeaderAlias("id","编号");
writer.addHeaderAlias("name","名字");
writer.addHeaderAlias("age","年龄");
writer.addHeaderAlias("birth","生日");
//3. 先输出一行标题(参数1是跨列数, 从0开始. 参数2 是标题字符串)
writer.merge(3,"标题");
//4. 模拟list集合数据
List<User> users = getUsers();
//5. 将users数据输出到excel文件中.
writer.write(users,true);// true表示并输出标题。
//6. 将填充数据后的excel文件保存在d盘文件中.
writer.flush(new FileOutputStream("D:/users.xlsx"));
}
private List<User> getUsers(){
List<User> list = new ArrayList<>();
list.add(new User("1001","张三",18,new Date()));
list.add(new User("1002","张三",18,new Date()));
list.add(new User("1003","张三",18,new Date()));
list.add(new User("1004","张三",18,new Date()));
return list;
}
(2)Excel导入
@Test
public void HutollUploadExcelTest() throws FileNotFoundException {
//1. 创建一个Excel读取工具reader
ExcelReader reader = ExcelUtil.getReader(new FileInputStream("D:/users.xlsx"));
//2. 设置读取的数据的别名和封装的实体的属性对应关系.
reader.addHeaderAlias("编号","id");
reader.addHeaderAlias("名字","name");
reader.addHeaderAlias("年龄","age");
reader.addHeaderAlias("生日","birth");
List<User> users = reader.read(1, 2, User.class);
// 输出返回的users集合
System.out.println(users);
// 输出users的大小.
System.out.println(users.size());
}
到此这篇关于Java Hutool工具实现验证码生成及Excel文件的导入和导出的文章就介绍到这了,更多相关Java Hutool工具内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!