java多线程导入excel(poi)

导入excel util

  1 /**
  2  * @Description: excel导入工具类
  3
  4  * @Author: hg
  5
  6  * @CreateDate: 2019/6/4 11:58
  7
  8  */
  9 @SuppressWarnings("all")
 10 public class POIUtil<T> {
 11
 12     private Logger logger = LoggerFactory.getLogger(this.getClass());
 13
 14     private Workbook wb;
 15
 16     private String[] property;
 17
 18     private Class<T> c;
 19
 20     private String filePath;
 21
 22     private int startRow;
 23
 24     private int startColumn;
 25
 26     //是否需要hash
 27     private boolean isHash = false;
 28
 29     //存放hash集合
 30     private HashSet<Integer> hashSet;
 31   
 32     private CopyOnWriteArrayList beanList;
 33
 34     public CopyOnWriteArrayList getBeanList() {
 35         return beanList;
 36     }
 37
 38     public POIUtil(String[] property, Class<T> c, String filePath, int startRow, int startColumn) {
 39         this.property = property;
 40         this.c = c;
 41         this.filePath = filePath;
 42         this.wb = getWorkbook(filePath);
 43         this.startRow = startRow;
 44         this.startColumn = startColumn;
 45         this.beanList = new CopyOnWriteArrayList();
 46     }
 47
 48     /**
 49      * @Description:
 50      * @Param: [property 类的属性字符串数组, c class对下你给, filePath excel地址,
 51      * startRow 开始行, startColumn 开始列, hashSet 不需要必填,hash校验]
 52      * @return:
 53      * @Author: hg
 54      * @Date: 2019/6/4
 55      */
 56     public POIUtil(String[] property, Class<T> c, String filePath, int startRow, int startColumn, HashSet<Integer> hashSet) {
 57         this.property = property;
 58         this.c = c;
 59         this.filePath = filePath;
 60         this.wb = getWorkbook(filePath);
 61         this.startRow = startRow;
 62         this.startColumn = startColumn;
 63         this.hashSet = hashSet;
 64         this.isHash = true;
 65         this.beanList = new CopyOnWriteArrayList();
 66     }
 67
 68     /**
 69      * @Description:
 70      * @Param: [startSheet sheet开始, endSheet sheet结束]
 71      * @return: void
 72      * @Author: hg
 73      * @Date: 2019/6/4
 74      */
 75     public void getBeanList(int startSheet, int endSheet) throws IllegalAccessException, InstantiationException, InvocationTargetException {
 76         HashMap<String, String> valueMap = new HashMap<>();
 77         for (int sheetNum = startSheet; sheetNum < endSheet; sheetNum++) {
 78             Sheet sheet = wb.getSheetAt(sheetNum);
 79             for (int rowNum = startRow; rowNum < sheet.getPhysicalNumberOfRows(); rowNum++) {
 80                 Row row = sheet.getRow(rowNum);
 81                 for (int i = 0, columnNum = startColumn; i < property.length; i++, columnNum++) {
 82                     Cell cell = row.getCell(columnNum);
 83                     valueMap.put(property[i], getCellValue(cell, cell.getCellType()));
 84                 }
 85                 //这里使用clone效率更高
 86                 T t = c.newInstance();
 87                 BeanUtils.populate(t, valueMap);
 88
 89                 //校验非空值
 90                 try {
 91                     ValidatorUtils.validateEntity(t);
 92                 } catch (WLHSEException e) {
 93                     continue;
 94                 }
 95
 96                 //hash校验
 97                 if (isHash) {
 98                     synchronized (hashSet) {
 99                         if (hashSet.contains(t.hashCode()))
100                             continue;
101                         hashSet.add(t.hashCode());
102                     }
103                 }
104                 beanList.add(t);
105             }
106         }
107     }
108
109     private Workbook getWorkbook(String filePath) {
110         Workbook wb = null;
111         try {
112             if (null != filePath) {
113                 FileInputStream fis = new FileInputStream(filePath);
114                 if (filePath.endsWith(".xls")) {
115                     wb = new HSSFWorkbook(fis);
116                 } else if (filePath.endsWith(".xlsx")) {
117                     wb = new XSSFWorkbook(fis);
118                 }
119                 return wb;
120             }
121         } catch (Exception e) {
122             logger.error(e.getMessage(), e);
123         }
124         return null;
125     }
126
127     private String getCellValue(Cell rowCell, int rowCellType) {
128         String value = "";
129         switch (rowCellType) {
130             case Cell.CELL_TYPE_STRING:
131                 value = rowCell.getStringCellValue();
132                 break;
133             case Cell.CELL_TYPE_NUMERIC:
134                 String dataFormat = rowCell.getCellStyle().getDataFormatString();
135                 AtomicReference<Boolean> isDate = new AtomicReference<>(false);
136                 if (DateUtil.isCellDateFormatted(rowCell)) {
137                     value = new SimpleDateFormat("yyyy-MM-dd").format(DateUtil.getJavaDate(rowCell.getNumericCellValue()));
138                 } else if (DateUtil.isCellInternalDateFormatted(rowCell)) {
139                     value = new SimpleDateFormat("yyyy-MM-dd").format(DateUtil.getJavaDate(rowCell.getNumericCellValue()));
140                 } else if (isDate.get()) {
141                     value = new SimpleDateFormat("yyyy-MM-dd").format(rowCell.getDateCellValue());
142                 } else if (dataFormat == null) {
143                     value = new SimpleDateFormat("yyyy-MM-dd").format(DateUtil.getJavaDate(rowCell.getNumericCellValue()));
144                 } else {
145                     if (dataFormat != null) {
146                         value = String.valueOf(rowCell.getNumericCellValue());
147                     } else {
148                         if (rowCell.getCellStyle().getDataFormatString().contains("$")) {
149                             value = "$" + rowCell.getNumericCellValue();
150                         } else if (rowCell.getCellStyle().getDataFormatString().contains("¥")) {
151                             value = "¥" + rowCell.getNumericCellValue();
152                         } else if (rowCell.getCellStyle().getDataFormatString().contains("¥")) {
153                             value = "¥" + rowCell.getNumericCellValue();
154                         } else if (rowCell.getCellStyle().getDataFormatString().contains("€")) {
155                             value = "€" + String.valueOf(rowCell.getNumericCellValue());
156                         } else {
157                             value = String.valueOf(rowCell.getNumericCellValue());
158                         }
159                     }
160                 }
161                 break;
162             case Cell.CELL_TYPE_BOOLEAN:
163                 value = String.valueOf(rowCell.getBooleanCellValue());
164                 break;
165             case Cell.CELL_TYPE_ERROR:
166                 value = ErrorEval.getText(rowCell.getErrorCellValue());
167                 break;
168             case Cell.CELL_TYPE_FORMULA:
169                 value = rowCell.getCellFormula();
170                 break;
171         }
172         return value;
173     }
174
175     public Workbook getWb() {
176         return wb;
177     }
178 }

导入excel线程

 1 public class POIThread implements Runnable {
 2     private int startSheet;
 3     private int endSheet;
 4     private POIUtil util;
 5     private CountDownLatch countDownLatch;
 6
 7
 8     POIThread(int startSheet, int endSheet, POIUtil util, CountDownLatch countDownLatch) {
 9         this.startSheet = startSheet;
10         this.endSheet = endSheet;
11         this.util = util;
12         this.countDownLatch = countDownLatch;
13     }
14
15     @Override
16     public void run() {
17         try {
18             util.getBeanList(startSheet, endSheet);
19         } catch (IllegalAccessException | InstantiationException | InvocationTargetException e) {
20             e.printStackTrace();
21         } finally {
22             countDownLatch.countDown();
23         }
24     }
25 }

执行线程

 1 public class POIThreadHelper {
 2     public void work(POIUtil util) {
 3         //一个sheet分配一个线程
 4         int runSize = util.getWb().getNumberOfSheets();
 5
 6         ExecutorService executor = Executors.newFixedThreadPool(runSize);
 7         CountDownLatch countDownLatch = new CountDownLatch(runSize);
 8
 9         for (int i = 0; i < runSize; i++) {
10             executor.execute(new POIThread(i, i + 1, util,countDownLatch));
11         }
12
13         try {
14             countDownLatch.await();
15         } catch (InterruptedException e) {
16             e.printStackTrace();
17         }
18         executor.shutdown();
19     }
20 }

测试

 1 @Test
 2     public void test1() throws IllegalAccessException, InvocationTargetException, InstantiationException {
 3         String path = "C:\\logs\\test.xls";
 4         String[] test = {"name", "sex"};
 5         POIUtil<Student> poiUtil = new POIUtil<Student>(test, Student.class, path, 1, 0);
 6         POIThreadHelper helper = new POIThreadHelper();
 7         helper.work(poiUtil);
 8         for (Object o : poiUtil.getBeanList()) {
 9             System.out.println(o.toString());
10         }
11     }

结果

原文地址:https://www.cnblogs.com/Gang-Bryant/p/10972818.html

时间: 2024-08-30 15:20:53

java多线程导入excel(poi)的相关文章

java easyreport 导入excel、 txt 数据简单实现(一)

一直在看博客,却不知道怎么写,但是总是想写点什么,犹豫了两三天,决定还是写点东西吧,来和大家分享下. 今年上半年时候接到了一个需求,具体什么需求就不说了,要求导入excel数据,并提示每一行错误信息.接到手后,查看之前的导入excel报表的代码,发现只有初始化workBook和根据cell获取cell 字符串值得通用方法.觉得可利用的东西太少了,于是决定就构建一个通用的实现导入excel报表的工具包. 实现思路大致是这样的: 提供模板,模板包含读起始行.属性模板集合.读批次.校验出错中端. 添加

java代码导入excel数据至oracle

本文处理的excel格式为xlsx: 1.新建maven项目 <dependencies> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.14</version> </dependency> <dependency> <groupId>org.apa

java easyreport 导入excel、 txt 数据数据格式校验(六)

在大部分情况下我们需要对导入数据的内容.格式进行合法性验证,验证不通过需要我们提示错误信息. 导入xls数据内容 姓名 年龄 科目 分数 王老五 12 语文 80 柯景腾 13 语文 78 沈佳宜 14 语文 88 王小贱 15 语文 60 黄小仙 12 语文 54 李大仁 14 语文 76 程又青 13 语文 58 陈寻 12 语文 67 方茴 12 语文 87 沈晓棠 13 语文 89 林嘉茉 14 语文 68 赵烨 14 语文 50 苏凯 12 语文 78 乔燃 13 语文 90 我们需要

java easyreport 导入excel、 txt 数据关联集合置入对象(三)

接上一节,获取的Student关联的Teacher集合有且只有一个,如何置入多个呢. 自定义StudentMatcher实现MatchAbled方法 package matcher; import java.util.List; import java.util.Map; import model.Student; import com.easyReport.read.MatchAbled; public class StudentMatcher implements MatchAbled<St

java easyreport 导入excel、 txt 数据复合属性(二)

在导入报表的时候,经常会遇到对象属性是集合或数组形似的,如学生会有多个老师,那么这种属性是集合或数组形式的报表如何设置,以及导入呢. Teacher类 package model; public class Teacher { private String name; private String sex; public String getName() { return name; } public void setName(String name) { this.name = name; }

Java jxl导入excel文件,导入的数字、身份证号码、手机号变成了科学计数法,解决方案

原文出自:https://blog.csdn.net/seesun2012 这是一个execl文件导入数据库操作,使用jxl解析execl导入数据库过程出现了科学计数法,与想要导入的数据不匹配,以下是案例以及解决方案: 导入成功后示例: 1.手机号:15388886666 科学计数法:1.54E+10 2.数字:123456789000000 科学计数法:1.23E+14 3.身份证:432222198808083789 科学计数法:4.32E+17 解决思路: 1.判断是否为数字类型(NUMB

java easyreport 导入excel、 txt 数据行列索引(四)

姓名 年龄 科目 分数 教师姓名 教师性别 王老五 12 语文 80 张三丰 男 我们要求导入数据中不包含科目和分数. 导入demo TestExcelIndex类 package example; import java.io.File; import java.io.FileInputStream; import java.util.List; import java.util.Map; import model.Student; import test.AbstractExcelTest;

java数据导入Excel中

首先需要一个JXL包,下载地址:http://download.csdn.net/source/292830 1.生成EXCEL需要手动写查询语句把ORACLE数据库中的数据查询出来,再通过操作写到EXCEL文件里面. 2.通过EXCEL把数据读取到ORACLE,同样需要去读取EXCEL工作薄里面的内容,再通过INSERT语句去插入数据库操作. 示例: 包括从Excel读取数据,生成新的Excel,以及修改Excel java代码: package common.util; import jxl

java easyreport 导入excel、 txt 数据txt按字节导入(七)

有时候导入txt文件不一定是采用分隔符方式导入,而是采用按字节.字符长度导入,比如银联对账文件. 导入txt数据 姓名 年龄科目分数 陈寻  12语文67 王老五12语文80 柯景腾13语文78 沈佳宜14语文88 王小贱15语文60 黄小仙12语文54 李大仁14语文76 程又青13语文58 方茴  12语文87 沈晓棠13语文89 林嘉茉14语文68 赵烨  14语文50 苏凯  12语文78 乔燃  13语文90 我们采用iso8859-1单字节编码读取文件数据,一个汉字占2字节. 导入d