首页 文章 精选 留言 我的

精选列表

搜索[java脚本],共10000篇文章
优秀的个人博客,低调大师

一行代码完成 JAVA 的 EXCEL 读写——EasyExcel 的方法封装

前段时间在 github 上发现了阿里的 EasyExcel 项目,觉得挺不错的,就写了一个简单的方法封装,做到只用一个函数就完成 Excel 的导入或者导。刚好前段时间更新修复了一些 BUG,就把我的这个封装分享出来,请多多指教 附上源码:https://github.com/HowieYuan/easyexcel-method-encapsulation EasyExcel EasyExcel 的 github 地址: https://github.com/alibaba/easyexcelEasyExcel 的官方介绍: 可以看到 EasyExcel 最大的特点就是使用内存少,当然现在它的功能还比较简单,能够面对的复杂场景比较少,不过基本的读写完全可以满足。 一. 依赖 首先是添加该项目的依赖,目前的版本是 1.0.2 <dependency> <groupId>com.alibaba</groupId> <artifactId>easyexcel</artifactId> <version>1.0.2</version> </dependency> 二. 需要的类 1. ExcelUtil 工具类,可以直接调用该工具类的方法完成 Excel 的读或者写 2. ExcelListener 监听类,可以根据需要与自己的情况,自定义处理获取到的数据,我这里只是简单地把数据添加到一个 List 里面。 public class ExcelListener extends AnalysisEventListener { //自定义用于暂时存储data。 //可以通过实例获取该值 private List<Object> datas = new ArrayList<>(); /** * 通过 AnalysisContext 对象还可以获取当前 sheet,当前行等数据 */ @Override public void invoke(Object object, AnalysisContext context) { //数据存储到list,供批量处理,或后续自己业务逻辑处理。 datas.add(object); //根据自己业务做处理 doSomething(object); } private void doSomething(Object object) { } @Override public void doAfterAllAnalysed(AnalysisContext context) { /* datas.clear(); 解析结束销毁不用的资源 */ } public List<Object> getDatas() { return datas; } public void setDatas(List<Object> datas) { this.datas = datas; } } 3. ExcelWriterFactroy 用于导出多个 sheet 的 Excel,通过多次调用 write 方法写入多个 sheet 4. ExcelException 捕获相关 Exception 三. 读取 Excel 读取 Excel 时只需要调用 ExcelUtil.readExcel() 方法 @RequestMapping(value = "readExcel", method = RequestMethod.POST) public Object readExcel(MultipartFile excel) { return ExcelUtil.readExcel(excel, new ImportInfo()); } 其中 excel 是 MultipartFile 类型的文件对象,而 new ImportInfo() 是该 Excel 所映射的实体对象,需要继承 BaseRowModel 类,如: public class ImportInfo extends BaseRowModel { @ExcelProperty(index = 0) private String name; @ExcelProperty(index = 1) private String age; @ExcelProperty(index = 2) private String email; /* 作为 excel 的模型映射,需要 setter 方法 */ public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } } 作为映射实体类,通过 @ExcelProperty 注解与 index 变量可以标注成员变量所映射的列,同时不可缺少 setter 方法 四. 导出 Excel 1. 导出的 Excel 只拥有一个 sheet 只需要调用 ExcelUtil.writeExcelWithSheets() 方法: @RequestMapping(value = "writeExcel", method = RequestMethod.GET) public void writeExcel(HttpServletResponse response) throws IOException { List<ExportInfo> list = getList(); String fileName = "一个 Excel 文件"; String sheetName = "第一个 sheet"; ExcelUtil.writeExcel(response, list, fileName, sheetName, new ExportInfo()); } fileName,sheetName 分别是导出文件的文件名和 sheet 名,new ExportInfo() 为导出数据的映射实体对象,list 为导出数据。 对于映射实体类,可以根据需要通过 @ExcelProperty 注解自定义表头,当然同样需要继承 BaseRowModel 类,如: public class ExportInfo extends BaseRowModel { @ExcelProperty(value = "姓名" ,index = 0) private String name; @ExcelProperty(value = "年龄",index = 1) private String age; @ExcelProperty(value = "邮箱",index = 2) private String email; @ExcelProperty(value = "地址",index = 3) private String address; } value 为列名,index 为列的序号 如果需要复杂一点,可以实现如下图的效果: 对应的实体类写法如下: public class MultiLineHeadExcelModel extends BaseRowModel { @ExcelProperty(value = {"表头1","表头1","表头31"},index = 0) private String p1; @ExcelProperty(value = {"表头1","表头1","表头32"},index = 1) private String p2; @ExcelProperty(value = {"表头3","表头3","表头3"},index = 2) private int p3; @ExcelProperty(value = {"表头4","表头4","表头4"},index = 3) private long p4; @ExcelProperty(value = {"表头5","表头51","表头52"},index = 4) private String p5; @ExcelProperty(value = {"表头6","表头61","表头611"},index = 5) private String p6; @ExcelProperty(value = {"表头6","表头61","表头612"},index = 6) private String p7; @ExcelProperty(value = {"表头6","表头62","表头621"},index = 7) private String p8; @ExcelProperty(value = {"表头6","表头62","表头622"},index = 8) private String p9; } 2. 导出的 Excel 拥有多个 sheet 调用 ExcelUtil.writeExcelWithSheets() 处理第一个 sheet,之后调用 write() 方法依次处理之后的 sheet,最后使用 finish() 方法结束 public void writeExcelWithSheets(HttpServletResponse response) throws IOException { List<ExportInfo> list = getList(); String fileName = "一个 Excel 文件"; String sheetName1 = "第一个 sheet"; String sheetName2 = "第二个 sheet"; String sheetName3 = "第三个 sheet"; ExcelUtil.writeExcelWithSheets(response, list, fileName, sheetName1, new ExportInfo()) .write(list, sheetName2, new ExportInfo()) .write(list, sheetName3, new ExportInfo()) .finish(); } write 方法的参数为当前 sheet 的 list 数据,当前 sheet 名以及对应的映射类

优秀的个人博客,低调大师

(四)Java并发学习笔记--线程不安全类与写法

常见线程不安全的类有哪些呢 下图中,我们只画出了最常见的几种情况,我们常见的Collections集合都是线程不安全的 StringBuilder-demo: @Slf4j public class StringExample1 { //请求总数 public static int clientTotal = 5000; //同时并发执行的线程数 public static int threadTotal = 200; public static StringBuilder stringBuilder = new StringBuilder(); private static void update() { stringBuilder.append("1"); } public static void main(String[] args)throws Exception { //定义线程池 ExecutorService executorService = Executors.newCachedThreadPool(); //定义信号量 final Semaphore semaphore = new Semaphore(threadTotal); //定义计数器闭锁 final CountDownLatch countDownLatch = new CountDownLatch(clientTotal); for (int i = 0; i < clientTotal; i++) { executorService.execute(()->{ try { semaphore.acquire(); update(); semaphore.release(); } catch (Exception e) { log.error("exception",e); } countDownLatch.countDown(); }); } countDownLatch.await(); executorService.shutdown(); log.info("size:{}",stringBuilder.length()); } } 我测试的时候输出为,4985(因为线程不安全,所以每次的输出可能是不同的),如果StringBuilder类为线程安全的话,输出应该为5000 StringBuffer-demo @Slf4j public class StringExample2 { //请求总数 public static int clientTotal = 5000; //同时并发执行的线程数 public static int threadTotal = 200; public static StringBuffer stringBuffer = new StringBuffer(); private static void update() { stringBuffer.append("1"); } public static void main(String[] args)throws Exception { //定义线程池 ExecutorService executorService = Executors.newCachedThreadPool(); //定义信号量 final Semaphore semaphore = new Semaphore(threadTotal); //定义计数器闭锁 final CountDownLatch countDownLatch = new CountDownLatch(clientTotal); for (int i = 0; i < clientTotal; i++) { executorService.execute(()->{ try { semaphore.acquire(); update(); semaphore.release(); } catch (Exception e) { log.error("exception",e); } countDownLatch.countDown(); }); } countDownLatch.await(); executorService.shutdown(); log.info("size:{}",stringBuffer.length()); } } 输出为5000,且多次测试结果均为5000,证明StringBuffer类是线程安全的,通过看StringBuffer的实现可发现,其所有的实现都是加了synchronized关键字的,虽然可以保证线程安全但是性能是有损耗的,这也证明了StringBuilder的存在价值,如果定义StringBuilder为局部变量时是没有线程安全问题的,这就用到了上篇博客我们讲的堆栈封闭原理 simpleDateFormat-demo1 @Slf4j public class DateFormatExample1 { private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd"); //请求总数 public static int clientTotal = 5000; //同时并发执行的线程数 public static int threadTotal = 200; private static void update() { try { simpleDateFormat.parse("20180208"); } catch (ParseException e) { log.error("parse exception",e); } } public static void main(String[] args)throws Exception { //定义线程池 ExecutorService executorService = Executors.newCachedThreadPool(); //定义信号量 final Semaphore semaphore = new Semaphore(threadTotal); //定义计数器闭锁 final CountDownLatch countDownLatch = new CountDownLatch(clientTotal); for (int i = 0; i < clientTotal; i++) { executorService.execute(()->{ try { semaphore.acquire(); update(); semaphore.release(); } catch (Exception e) { log.error("exception",e); } countDownLatch.countDown(); }); } countDownLatch.await(); executorService.shutdown(); } } 运行结果如下: 因为simpleDateFormat为线程不安全的类,所以在多线程访问的时候出现了异常 simpleDateFormat-demo2: @Slf4j public class DateFormatExample2 { //请求总数 public static int clientTotal = 5000; //同时并发执行的线程数 public static int threadTotal = 200; private static void update() { try { //用堆栈封闭的方式 SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd"); simpleDateFormat.parse("20180208"); } catch (ParseException e) { log.error("parse exception",e); } } public static void main(String[] args)throws Exception { //定义线程池 ExecutorService executorService = Executors.newCachedThreadPool(); //定义信号量 final Semaphore semaphore = new Semaphore(threadTotal); //定义计数器闭锁 final CountDownLatch countDownLatch = new CountDownLatch(clientTotal); for (int i = 0; i < clientTotal; i++) { executorService.execute(()->{ try { semaphore.acquire(); update(); semaphore.release(); } catch (Exception e) { log.error("exception",e); } countDownLatch.countDown(); }); } countDownLatch.await(); executorService.shutdown(); } } 此demo为demo1的改进版,将SimpleDateFormat声明为局部变量,运用了堆栈封闭的方式保证了线程安全,运行此demo是没有异常抛出的 jodatime-demo import org.joda.time.DateTime; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; @Slf4j public class DateFormatExample3 { //请求总数 public static int clientTotal = 5000; //同时并发执行的线程数 public static int threadTotal = 200; private static DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyyyMMdd"); private static void update(int i) { log.info("{},{}",i,DateTime.parse("20180208", dateTimeFormatter).toDate()); } public static void main(String[] args)throws Exception { //定义线程池 ExecutorService executorService = Executors.newCachedThreadPool(); //定义信号量 final Semaphore semaphore = new Semaphore(threadTotal); //定义计数器闭锁 final CountDownLatch countDownLatch = new CountDownLatch(clientTotal); for (int i = 0; i < clientTotal; i++) { final int count = i; executorService.execute(()->{ try { semaphore.acquire(); update(count); semaphore.release(); } catch (Exception e) { log.error("exception",e); } countDownLatch.countDown(); }); } countDownLatch.await(); executorService.shutdown(); } } 此demo引用了joda.time包,保证了线程安全,在实际的开发中,我们更推荐做日期转换的时候使用此包,这种处理方法不仅能保证线程安全,而且还有其它的优势。我导入的包如下: <dependency> <groupId>joda-time</groupId> <artifactId>joda-time</artifactId> <version>2.9</version> </dependency> 以下我们做ArrayList,HashMap,HashSet的实例演示,它们都是线程不安全的,还好我们一般都将它们定义为局部变量(堆栈封闭),如果我们将它们定义为成员变量或static修饰的变量,在多个线程同时访问的时候就很容易出问题。 ArrayList-demo @Slf4j public class ArrayListExample { //请求总数 public static int clientTotal = 5000; //同时并发执行的线程数 public static int threadTotal = 200; //arraylist是线程不安全的 private static List<Integer> list = new ArrayList<>(); private static void update(int i) { list.add(i); } public static void main(String[] args)throws Exception { //定义线程池 ExecutorService executorService = Executors.newCachedThreadPool(); //定义信号量 final Semaphore semaphore = new Semaphore(threadTotal); //定义计数器闭锁 final CountDownLatch countDownLatch = new CountDownLatch(clientTotal); for (int i = 0; i < clientTotal; i++) { final int count = i; executorService.execute(()->{ try { semaphore.acquire(); update(count); semaphore.release(); } catch (Exception e) { log.error("exception",e); } countDownLatch.countDown(); }); } countDownLatch.await(); executorService.shutdown(); log.info("size:{}", list.size()); } } 如果是线程安全的输出应该为5000,实际输出为4945,且每次运行输出的值可能不一样,所以它是线程不安全的 HashSet-demo @Slf4j public class HashSetExample { //请求总数 public static int clientTotal = 5000; //同时并发执行的线程数 public static int threadTotal = 200; //HashSet是线程不安全的 private static Set<Integer> set = new HashSet<>(); private static void update(int i) { set.add(i); } public static void main(String[] args)throws Exception { //定义线程池 ExecutorService executorService = Executors.newCachedThreadPool(); //定义信号量 final Semaphore semaphore = new Semaphore(threadTotal); //定义计数器闭锁 final CountDownLatch countDownLatch = new CountDownLatch(clientTotal); for (int i = 0; i < clientTotal; i++) { final int count = i; executorService.execute(()->{ try { semaphore.acquire(); update(count); semaphore.release(); } catch (Exception e) { log.error("exception",e); } countDownLatch.countDown(); }); } countDownLatch.await(); executorService.shutdown(); log.info("size:{}", set.size()); } } 输出为4985,是线程不安全的(线程安全的话输出为5000) HashMap-demo @Slf4j public class HashMapExample { //请求总数 public static int clientTotal = 5000; //同时并发执行的线程数 public static int threadTotal = 200; //HashMap是线程不安全的 private static Map<Integer,Integer> map = new HashMap<>(); private static void update(int i) { map.put(i,i); } public static void main(String[] args)throws Exception { //定义线程池 ExecutorService executorService = Executors.newCachedThreadPool(); //定义信号量 final Semaphore semaphore = new Semaphore(threadTotal); //定义计数器闭锁 final CountDownLatch countDownLatch = new CountDownLatch(clientTotal); for (int i = 0; i < clientTotal; i++) { final int count = i; executorService.execute(()->{ try { semaphore.acquire(); update(count); semaphore.release(); } catch (Exception e) { log.error("exception",e); } countDownLatch.countDown(); }); } countDownLatch.await(); executorService.shutdown(); log.info("size:{}", map.size()); } } 输出为4886(且每次运行输出值可能不同),是线程不安全的(线程安全的话输出为5000) 线程不安全的写法 典型的线程不安全的写法是:先检查,再执行 if(condition(a)){handle(a);} 就算a是一个线程安全的类所对应的对象,对a的处理handle(a)也是原子性的,但由于这两步之间的不是原子性的也会引发线程安全问题,如A、B两个线程都通过了a的判断条件,A线程执行handle(a)之后,a已经不符合condition(a)的判断条件了,可是此时B线程仍然要执行handle(a),这就引发了线程安全问题。

资源下载

更多资源
优质分享App

优质分享App

近一个月的开发和优化,本站点的第一个app全新上线。该app采用极致压缩,本体才4.36MB。系统里面做了大量数据访问、缓存优化。方便用户在手机上查看文章。后续会推出HarmonyOS的适配版本。

Mario

Mario

马里奥是站在游戏界顶峰的超人气多面角色。马里奥靠吃蘑菇成长,特征是大鼻子、头戴帽子、身穿背带裤,还留着胡子。与他的双胞胎兄弟路易基一起,长年担任任天堂的招牌角色。

Nacos

Nacos

Nacos /nɑ:kəʊs/ 是 Dynamic Naming and Configuration Service 的首字母简称,一个易于构建 AI Agent 应用的动态服务发现、配置管理和AI智能体管理平台。Nacos 致力于帮助您发现、配置和管理微服务及AI智能体应用。Nacos 提供了一组简单易用的特性集,帮助您快速实现动态服务发现、服务配置、服务元数据、流量管理。Nacos 帮助您更敏捷和容易地构建、交付和管理微服务平台。

Spring

Spring

Spring框架(Spring Framework)是由Rod Johnson于2002年提出的开源Java企业级应用框架,旨在通过使用JavaBean替代传统EJB实现方式降低企业级编程开发的复杂性。该框架基于简单性、可测试性和松耦合性设计理念,提供核心容器、应用上下文、数据访问集成等模块,支持整合Hibernate、Struts等第三方框架,其适用范围不仅限于服务器端开发,绝大多数Java应用均可从中受益。

用户登录
用户注册
修改密码
忘记密码