Java--POI技术处理Excel表 .xls ..xlsx两种格式的导入操作

举报
吾日三省贾斯汀 发表于 2021/09/10 00:48:44 2021/09/10
【摘要】 一、说明 原文标题====SpringMvc+POI 处理Excel的导入操作功能==== 提到了ImportExcelUtil.java(Excel解析工具类)、UploadExcelControl.java (Spring控制器)、InfoVo.java(保存Excel数据对应的对象)、main.jsp(前端代码)以及配置文件we...

一、说明

原文标题====SpringMvc+POI 处理Excel的导入操作功能====

提到了ImportExcelUtil.java(Excel解析工具类)、UploadExcelControl.java (Spring控制器)、InfoVo.java(保存Excel数据对应的对象)、main.jsp(前端代码)以及配置文件web.xml、springmvc-servlet.xml(只做简单配置)、applicationContext-base.xml等。

本文只提Controller层、ImportExcelUtil工具类两部分,原文中这两部分导入功能可能会有一些小问题,具体可看原文网友评论。

我对原文导入部分代码进行略微修改后,导入功能已实际运用当中,没发现问题。

 

二、功能代码

首先先感谢下原文博主,然后上代码!!!!!
 

Controller层部分代码


  
  1. // 单号信息service
  2. @Autowired
  3. public OrderService orderService ; //服务层改为自己的
  4. /**
  5. * 一键上传Excel表信息
  6. *
  7. * @author Justin
  8. *
  9. */
  10. @RequestMapping("order_add.action")
  11. public @ResponseBody List<String> uploadadd(MultipartFile myFile, HttpServletResponse res) throws IOException {
  12. List<String> errorList = new ArrayList<String>();
  13. try {
  14. ImportExcelUtil util = new ImportExcelUtil();
  15. InputStream input = null;
  16. List<List<Object>> lists = null;
  17. if(myFile.isEmpty()) {
  18. log.error("文件不存在!");
  19. }else {
  20. if (errorList.size() == 0) {
  21. String fileName = myFile.getOriginalFilename();
  22. input = myFile.getInputStream();
  23. lists = util.getBankListByExcel(input, fileName);
  24. input.close();
  25. //循环将excel中的数据存入库
  26. for(int i=1; i<lists.size(); i++) {
  27. List<Object> list = lists.get(i);
  28. Order order= new Order(); //实体类,改为自己的
  29. order.setOrderNumber(util.getFormat(String.valueOf(list.get(0))));
  30. order.setAddress(util.getFormat(String.valueOf(list.get(1))));
  31. order.setPhone(util.getFormat(String.valueOf(list.get(2))));
  32. orderService.add(order);
  33. }
  34. }
  35. }
  36. } catch (Exception e) {
  37. errorList.add("导入单号数据错误");
  38. e.printStackTrace();
  39. log.error("系统错误", e.fillInStackTrace());
  40. }
  41. return errorList;
  42. }


ImportExcelUtil工具类

 


  
  1. package com.sale.util;
  2. import java.io.InputStream;
  3. import java.text.DecimalFormat;
  4. import java.text.SimpleDateFormat;
  5. import java.util.ArrayList;
  6. import java.util.Date;
  7. import java.util.List;
  8. import org.apache.poi.hssf.usermodel.HSSFDateUtil;
  9. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  10. import org.apache.poi.ss.usermodel.Cell;
  11. import org.apache.poi.ss.usermodel.Row;
  12. import org.apache.poi.ss.usermodel.Sheet;
  13. import org.apache.poi.ss.usermodel.Workbook;
  14. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  15. /**
  16. * excel文件上传Util
  17. *
  18. * @author Justin
  19. *
  20. */
  21. public class ImportExcelUtil {
  22. private final static String Excel_2003 = ".xls"; //2003 版本的excel
  23. private final static String Excel_2007 = ".xlsx"; //2007 版本的excel
  24. /**
  25. * @param in
  26. * @param fileName
  27. * @param columNum 自定义列数
  28. * @return
  29. * */
  30. public List<List<Object>> getBankListByExcel(InputStream in,String fileName) throws Exception{
  31. List<List<Object>> list = null;
  32. //创建Excel工作簿
  33. Workbook work = this.getWorkbook(in, fileName);
  34. if(work == null) {
  35. throw new Exception("创建Excel工作簿为空!");
  36. }
  37. Sheet sheet = null;
  38. Row row = null;
  39. Cell cell = null;
  40. list = new ArrayList<List<Object>>();
  41. //遍历Excel中的所有sheet
  42. for(int i = 0; i<work.getNumberOfSheets(); i++) {
  43. sheet = work.getSheetAt(i);
  44. if(sheet == null) {continue;}
  45. //遍历当前sheet中的所有行
  46. //int totalRow = sheet.getPhysicalNumberOfRows();//如果excel有格式,这种方式取值不准确
  47. int totalRow = sheet.getPhysicalNumberOfRows();
  48. for(int j = sheet.getFirstRowNum(); j<totalRow; j++) {
  49. row = sheet.getRow(j);
  50. if(row != null && !"".equals(row)) {
  51. //获取第一个单元格的数据是否存在
  52. Cell fristCell=row.getCell(0);
  53. if(fristCell!=null){
  54. //遍历所有的列
  55. List<Object> li = new ArrayList<Object>();
  56. //int totalColum = row.getLastCellNum();
  57. for(int y = row.getFirstCellNum(); y<row.getLastCellNum(); y++) {
  58. cell = row.getCell(y);
  59. String callCal = this.getCellValue(cell)+"";
  60. li.add(callCal);
  61. }
  62. list.add(li);
  63. }
  64. }
  65. }
  66. }
  67. in.close();
  68. return list;
  69. }
  70. /**
  71. * 描述:根据文件后缀,自动适应上传文件的版本
  72. * @param inStr,fileName
  73. * @return
  74. * @throws Exception
  75. * */
  76. public Workbook getWorkbook(InputStream inStr,String fileName) throws Exception {
  77. Workbook work = null;
  78. String fileType = fileName.substring(fileName.lastIndexOf("."));
  79. if(Excel_2003.equals(fileType)){
  80. work=new HSSFWorkbook(inStr);//2003 版本的excel
  81. }else if(Excel_2007.equals(fileType)) {
  82. work=new XSSFWorkbook(inStr);//2007 版本的excel
  83. }else {
  84. throw new Exception("解析文件格式有误!");
  85. }
  86. return work;
  87. }
  88. /**
  89. * 描述:对表格中数值进行格式化
  90. * @param cell
  91. * @return
  92. * */
  93. public Object getCellValue(Cell cell) {
  94. Object value = null;
  95. DecimalFormat df1 = new DecimalFormat("0");//格式化number,string字符
  96. SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd");//日期格式化
  97. DecimalFormat df2 = new DecimalFormat("0.00");//格式化数字
  98. if(cell !=null && !"".equals(cell)) {
  99. switch (cell.getCellType()) {
  100. case Cell.CELL_TYPE_STRING:
  101. value = cell.getRichStringCellValue().getString();
  102. break;
  103. case Cell.CELL_TYPE_NUMERIC:
  104. if("General".equals(cell.getCellStyle().getDataFormatString())) {
  105. value = df1.format(cell.getNumericCellValue());
  106. }else if("m/d/yy".equals(cell.getCellStyle().getDataFormatString())) {
  107. value = sdf.format(cell.getDateCellValue());
  108. }else if(HSSFDateUtil.isCellDateFormatted(cell)){
  109. Date date = cell.getDateCellValue();
  110. value = sdf.format(date);
  111. }
  112. else {
  113. value = df2.format(cell.getNumericCellValue());
  114. }
  115. break;
  116. case Cell.CELL_TYPE_BOOLEAN:
  117. value = cell.getBooleanCellValue();
  118. break;
  119. case Cell.CELL_TYPE_BLANK:
  120. value = "";
  121. break;
  122. default:
  123. break;
  124. }
  125. }
  126. return value;
  127. }
  128. public String getFormat(String str) {
  129. if(str.equals("null")) {
  130. str="";
  131. return str;
  132. }else{
  133. return str;
  134. }
  135. }
  136. public Integer getFormats(Integer str) {
  137. if(str==null) {
  138. str=0;
  139. return str;
  140. }else{
  141. return str;
  142. }
  143. }
  144. }

 




附:

导入耗时测试代码(可忽略,根据需要往代码copy测试)

 


  
  1. //方法第一行代码
  2. long startTime = System.currentTimeMillis();
  3. //方法最后一行代码
  4. long endTime = System.currentTimeMillis();
  5. //long类型时间差,单位毫秒
  6. long timeLong = endTime - startTime;
  7. //long类型时间差转为double类型时间差,单位毫秒
  8. double timeDouble= Double.parseDouble(Long.toString(timeLong));
  9. System.out.println("该方法执行时间为" + timeDouble+ "毫秒,即" + timeDouble/(double)1000 + "秒");


我的1、2、3、4次测试结果分别为如下:
该POI技术导入excel表数据量为16880条到数据库耗时为11569.0毫秒,即11.569秒
该POI技术导入excel表数据量为16880条到数据库耗时为7451.0毫秒,即7.451秒
该POI技术导入excel表数据量为16880条到数据库耗时为7258.0毫秒,即7.258秒
该POI技术导入excel表数据量为16880条到数据库耗时为7478.0毫秒,即7.478秒

文章来源: blog.csdn.net,作者:吾日三省贾斯汀,版权归原作者所有,如需转载,请联系作者。

原文链接:blog.csdn.net/JustinQin/article/details/78769789

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。