当前位置:   article > 正文

java 读取excel数据 poi导入excel 数据 java导入excel表格 java import excel_java导入excel读取指定单元格数据

java导入excel读取指定单元格数据

        java 读取excel数据 poi导入excel 数据 java导入excel表格 java import excel

一、说明

        1、在实际开发中,可能有需求需要将excel导入到业务系统中,具体实现可以使用Apache poi 来实现。

        2、依赖pom如下:

  1. <dependency>
  2. <groupId>org.apache.poi</groupId>
  3. <artifactId>poi</artifactId>
  4. <version>3.15</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.apache.poi</groupId>
  8. <artifactId>poi-ooxml</artifactId>
  9. <version>3.15</version>
  10. </dependency>

二、代码实现

        1、创建ExcelImport 类,实现excel数据导入

  1. import java.io.File;
  2. import java.io.FileInputStream;
  3. import java.io.InputStream;
  4. import java.text.DecimalFormat;
  5. import java.text.SimpleDateFormat;
  6. import java.util.ArrayList;
  7. import java.util.Date;
  8. import java.util.List;
  9. import org.apache.poi.hssf.usermodel.HSSFCell;
  10. import org.apache.poi.hssf.usermodel.HSSFDateUtil;
  11. import org.apache.poi.hssf.usermodel.HSSFRow;
  12. import org.apache.poi.hssf.usermodel.HSSFSheet;
  13. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  14. import org.apache.poi.ss.usermodel.Cell;
  15. import org.apache.poi.ss.usermodel.DateUtil;
  16. import org.apache.poi.xssf.usermodel.XSSFCell;
  17. import org.apache.poi.xssf.usermodel.XSSFRow;
  18. import org.apache.poi.xssf.usermodel.XSSFSheet;
  19. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  20. import org.springframework.web.multipart.MultipartFile;
  21. /**
  22. * description: Excel 数据导入
  23. * @version v1.0
  24. * @author w
  25. * @date 2020年3月30日下午9:46:27
  26. **/
  27. public class ExcelImport {
  28. private ExcelImport INSTANSE = new ExcelImport();
  29. /**
  30. * excel 2003 suffix
  31. */
  32. private static final String EXCEL_XLS_SUFFIX = ".xls" ;
  33. /**
  34. * excel 2007 或以上 suffix
  35. */
  36. private static final String EXCEL_XLSX_SUFFIX = ".xlsx";
  37. /**
  38. * 分隔符 "."
  39. */
  40. public static final String POINT = ".";
  41. /**
  42. * description: 读取excel数据
  43. * @param file
  44. * @return List<List<Object>>
  45. * @version v1.0
  46. * @author w
  47. * @date 2020年3月31日 下午3:36:39
  48. */
  49. public static List<List<Object>> importFile (File file) throws Exception{
  50. if(file == null) {
  51. return null ;
  52. }
  53. if(file.getName().endsWith(EXCEL_XLS_SUFFIX)) {
  54. return readXls(new FileInputStream(file));
  55. }
  56. if(file.getName().endsWith(EXCEL_XLSX_SUFFIX)) {
  57. return readXlsx(new FileInputStream(file));
  58. }
  59. throw new RuntimeException("文件不对,必须是excel文件,后缀名以:"+EXCEL_XLS_SUFFIX + " 或者 "+ EXCEL_XLSX_SUFFIX);
  60. }
  61. /**
  62. * description: 导入excel --- 支持web
  63. * @param fileName
  64. * @param inputStream
  65. * @throws Exception
  66. * @return List<List<Object>>
  67. * @version v1.0
  68. * @author w
  69. * @date 2020年3月31日 下午4:51:01
  70. */
  71. public static List<List<Object>> importFile (MultipartFile multipartFile) throws Exception{
  72. if(multipartFile == null) {
  73. return null ;
  74. }
  75. if(multipartFile.getOriginalFilename().endsWith(EXCEL_XLS_SUFFIX)) {
  76. return readXls(multipartFile.getInputStream());
  77. }
  78. if(multipartFile.getOriginalFilename().endsWith(EXCEL_XLSX_SUFFIX)) {
  79. return readXlsx(multipartFile.getInputStream());
  80. }
  81. throw new RuntimeException("文件不对,必须是excel文件,后缀名以:"+EXCEL_XLS_SUFFIX + " 或者 "+ EXCEL_XLSX_SUFFIX);
  82. }
  83. /**
  84. * description: 读取03版excel
  85. * @param file
  86. * @return List<List<Object>>
  87. * @version v1.0
  88. * @author w
  89. * @date 2020年3月31日 下午3:38:44
  90. */
  91. private static List<List<Object>> readXls(InputStream inputStream) throws Exception {
  92. List<List<Object>> list = new ArrayList<>();
  93. // 读取excel
  94. HSSFWorkbook workbook = new HSSFWorkbook(inputStream);
  95. // 获取sheet 页数量
  96. int sheets = workbook.getNumberOfSheets();
  97. for(int num = 0 ; num < sheets ; num++ ) {
  98. HSSFSheet sheet = workbook.getSheetAt(num);
  99. if(null == sheet) {
  100. continue ;
  101. }
  102. // sheet 页的总行数
  103. int rows = sheet.getLastRowNum();
  104. // startRow 开始读取的行数 --- 第二行开始读
  105. for( int startRow = 1 ;startRow <= rows ; startRow ++) {
  106. HSSFRow row = sheet.getRow(startRow);
  107. List<Object> rowList = new ArrayList<>();
  108. if(null != row) {
  109. // row 行中的 单元格总个数
  110. short cells = row.getLastCellNum();
  111. for(int x = 0 ; x <= cells ; x++) {
  112. HSSFCell cell = row.getCell(x);
  113. if(null == cell) {
  114. rowList.add("");
  115. }else {
  116. rowList.add(getXlsValue(cell));
  117. }
  118. }
  119. list.add(rowList);
  120. }
  121. }
  122. }
  123. return list;
  124. }
  125. /**
  126. * description: 获取 03 版 excel数据
  127. * @param cell
  128. * @return String
  129. * @version v1.0
  130. * @author w
  131. * @date 2020年3月31日 下午3:54:14
  132. */
  133. private static String getXlsValue(HSSFCell cell) {
  134. if ( cell.getCellType() == cell.CELL_TYPE_BOOLEAN) {
  135. return String.valueOf(cell.getBooleanCellValue());
  136. } else if (cell.getCellType() == cell.CELL_TYPE_NUMERIC) {
  137. String cellValue = "";
  138. if(HSSFDateUtil.isCellDateFormatted(cell)){
  139. Date date = HSSFDateUtil.getJavaDate(cell.getNumericCellValue());
  140. cellValue = new SimpleDateFormat("yyyy/MM/dd").format(date);
  141. }else{
  142. DecimalFormat df = new DecimalFormat("#.##");
  143. cellValue = df.format(cell.getNumericCellValue());
  144. String strArr = cellValue.substring(cellValue.lastIndexOf(POINT)+1,cellValue.length());
  145. if(strArr.equals("00")){
  146. cellValue = cellValue.substring(0, cellValue.lastIndexOf(POINT));
  147. }
  148. }
  149. return cellValue;
  150. } else {
  151. // 其他类型的值,统一设置为 string
  152. // http://blog.csdn.net/ysughw/article/details/9288307
  153. cell.setCellType(Cell.CELL_TYPE_STRING);
  154. return String.valueOf(cell.getStringCellValue());
  155. }
  156. }
  157. /**
  158. * description: 读取07或以上版本的 excel
  159. * @param file
  160. * @throws Exception
  161. * @return List<List<Object>>
  162. * @version v1.0
  163. * @author w
  164. * @date 2020年3月31日 下午4:01:25
  165. */
  166. private static List<List<Object>> readXlsx(InputStream inputStream) throws Exception {
  167. List<List<Object>> list = new ArrayList<>();
  168. // 读取excel ,封装到 XSSFWorkbook 对象
  169. XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
  170. int sheets = workbook.getNumberOfSheets();
  171. for(int num = 0 ;num < sheets ; num++) {
  172. XSSFSheet sheet = workbook.getSheetAt(num);
  173. if(null == sheet) {
  174. continue ;
  175. }
  176. // 获取sheet页的总行数
  177. int rows = sheet.getLastRowNum();
  178. for(int startRow = 1 ; startRow <= rows ; startRow++ ) {
  179. // startRow 开始读取的行数, 从第二行开始读取
  180. XSSFRow row = sheet.getRow(startRow);
  181. List<Object> rowList = new ArrayList<>();
  182. if(null != row) {
  183. // 获取行总单元格个数
  184. short cells = row.getLastCellNum();
  185. for(int x = 0 ; x < cells ; x++) {
  186. XSSFCell cell = row.getCell(x);
  187. if(cell == null) {
  188. rowList.add("");
  189. }else {
  190. rowList.add(getXlsxValue(cell));
  191. }
  192. }
  193. list.add(rowList);
  194. }
  195. }
  196. }
  197. return list;
  198. }
  199. /**
  200. * description: 获取07或以上版本 excel 数据
  201. * @param cell
  202. * @return Object
  203. * @version v1.0
  204. * @author w
  205. * @date 2020年3月31日 下午4:09:03
  206. */
  207. private static Object getXlsxValue(XSSFCell cell) {
  208. if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
  209. return String.valueOf(cell.getBooleanCellValue());
  210. } else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
  211. String cellValue = "";
  212. if (DateUtil.isCellDateFormatted(cell)) {
  213. Date date = DateUtil.getJavaDate(cell.getNumericCellValue());
  214. cellValue = new SimpleDateFormat("yyyy/MM/dd").format(date);
  215. } else {
  216. DecimalFormat df = new DecimalFormat("#.##");
  217. cellValue = df.format(cell.getNumericCellValue());
  218. String strArr = cellValue.substring(cellValue.lastIndexOf(POINT) + 1, cellValue.length());
  219. if (strArr.equals("00")) {
  220. cellValue = cellValue.substring(0, cellValue.lastIndexOf(POINT));
  221. }
  222. }
  223. return cellValue;
  224. } else {
  225. // 其他类型的值,统一设置为 string
  226. // http://blog.csdn.net/ysughw/article/details/9288307
  227. //cell.setCellType(Cell.CELL_TYPE_STRING);
  228. return String.valueOf(cell.getStringCellValue());
  229. }
  230. }
  231. }

        2、测试,直接本地测试 :

  1. @Test
  2. public void test() {
  3. String path = "F:\\poi导出2.xlsx" ;
  4. File file = new File(path);
  5. try {
  6. List<List<Object>> importFile = ExcelImport.importFile(file);
  7. System.out.println(importFile);
  8. } catch (Exception e) {
  9. e.printStackTrace();
  10. }
  11. }

        3、查看控制中输出的数据和excel中的是否一致。

三、总结

        1、本示例使用的是 poi 3.15版的,其他版本可能需要做部分调整。

        2、对于导入excel数据类型转换,不一定考虑到全部,请根据实际业务情况调整。

        3、web情况下导入,请自行创建页面测试,ExcelImport 类中已经提供对应的方法支持。

        4、需要源码请私聊我,谢谢。

学习更多:

java 数据导出Excel java POI 导出数据Excel_HaHa_Sir的博客-CSDN博客_java导出excel 空格

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Cpp五条/article/detail/726023
推荐阅读
相关标签
  

闽ICP备14008679号