sunny123456

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

java中解析上传的excel文件(xls,xlsx)

一、在maven库中导入相关依赖


其中poi是解析xls格式的,poi-ooxml是解析xlsx格式的

  1. <!-- POI,excel解析相关 -->
  2. <dependency>
  3. <groupId>org.apache.poi</groupId>
  4. <artifactId>poi</artifactId>
  5. <version>3.17</version>
  6. </dependency>
  7. <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
  8. <dependency>
  9. <groupId>org.apache.poi</groupId>
  10. <artifactId>poi-ooxml</artifactId>
  11. <version>3.17</version>
  12. </dependency>
  13. <dependency>
  14. <groupId>net.sf.json-lib</groupId>
  15. <artifactId>json-lib</artifactId>
  16. <version>2.4</version>
  17. <classifier>jdk15</classifier>
  18. </dependency>

 

二、解析代码


  1. import java.io.File;
  2. import java.io.FileInputStream;
  3. import java.io.FileNotFoundException;
  4. import java.io.IOException;
  5. import java.text.DateFormat;
  6. import java.text.SimpleDateFormat;
  7. import java.util.Date;
  8. import java.util.HashMap;
  9. import java.util.Map;
  10. import org.apache.poi.hssf.usermodel.HSSFDateUtil;
  11. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  12. import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
  13. import org.apache.poi.poifs.filesystem.POIFSFileSystem;
  14. import org.apache.poi.ss.usermodel.Cell;
  15. import org.apache.poi.ss.usermodel.Row;
  16. import org.apache.poi.ss.usermodel.Sheet;
  17. import org.apache.poi.ss.usermodel.Workbook;
  18. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  19. import net.sf.json.JSONArray;
  20. import net.sf.json.JSONObject;
  21. import org.springframework.stereotype.Component;
  22. import sun.applet.Main;
  23. @Component
  24. public class ExcelResolve {
  25. public final String XLSX = ".xlsx";
  26. public final String XLS=".xls";
  27. /**
  28. * 获取Excel文件(.xls和.xlsx都支持)
  29. * @param file
  30. * @return 解析excle后的Json数据
  31. * @throws IOException
  32. * @throws FileNotFoundException
  33. * @throws InvalidFormatException
  34. */
  35. public JSONArray readExcel(File file) throws Exception{
  36. int res = checkFile(file);
  37. if (res == 0) {
  38. System.out.println("File not found");
  39. }else if (res == 1) {
  40. return readXLSX(file);
  41. }else if (res == 2) {
  42. return readXLS(file);
  43. }
  44. JSONArray array = new JSONArray();
  45. return array;
  46. }
  47. /**
  48. * 判断File文件的类型
  49. * @param file 传入的文件
  50. * @return 0-文件为空,1-XLSX文件,2-XLS文件,3-其他文件
  51. */
  52. public int checkFile(File file){
  53. if (file==null) {
  54. return 0;
  55. }
  56. String flieName = file.getName();
  57. if (flieName.endsWith(XLSX)) {
  58. return 1;
  59. }
  60. if (flieName.endsWith(XLS)) {
  61. return 2;
  62. }
  63. return 3;
  64. }
  65. /**
  66. * 读取XLSX文件
  67. * @param file
  68. * @return
  69. * @throws IOException
  70. * @throws InvalidFormatException
  71. */
  72. public JSONArray readXLSX(File file) throws InvalidFormatException, IOException{
  73. Workbook book = new XSSFWorkbook(file);
  74. Sheet sheet = book.getSheetAt(0);
  75. return read(sheet, book);
  76. }
  77. /**
  78. * 读取XLS文件
  79. * @param file
  80. * @return
  81. * @throws IOException
  82. * @throws FileNotFoundException
  83. */
  84. public JSONArray readXLS(File file) throws FileNotFoundException, IOException{
  85. POIFSFileSystem poifsFileSystem = new POIFSFileSystem(new FileInputStream(file));
  86. Workbook book = new HSSFWorkbook(poifsFileSystem);
  87. Sheet sheet = book.getSheetAt(0);
  88. return read(sheet, book);
  89. }
  90. /**
  91. * 解析数据
  92. * @param sheet 表格sheet对象
  93. * @param book 用于流关闭
  94. * @return
  95. * @throws IOException
  96. */
  97. public JSONArray read(Sheet sheet,Workbook book) throws IOException{
  98. int rowStart = sheet.getFirstRowNum(); // 首行下标
  99. int rowEnd = sheet.getLastRowNum(); // 尾行下标
  100. // 如果首行与尾行相同,表明只有一行,直接返回空数组
  101. if (rowStart == rowEnd) {
  102. book.close();
  103. return new JSONArray();
  104. }
  105. // 获取第一行JSON对象键
  106. Row firstRow = sheet.getRow(rowStart);
  107. int cellStart = firstRow.getFirstCellNum();
  108. int cellEnd = firstRow.getLastCellNum();
  109. Map<Integer, String> keyMap = new HashMap<Integer, String>();
  110. for (int j = cellStart; j < cellEnd; j++) {
  111. keyMap.put(j,getValue(firstRow.getCell(j), rowStart, j, book, true));
  112. }
  113. // 获取每行JSON对象的值
  114. JSONArray array = new JSONArray();
  115. for(int i = rowStart+1; i <= rowEnd ; i++) {
  116. Row eachRow = sheet.getRow(i);
  117. JSONObject obj = new JSONObject();
  118. StringBuffer sb = new StringBuffer();
  119. for (int k = cellStart; k < cellEnd; k++) {
  120. if (eachRow != null) {
  121. String val = getValue(eachRow.getCell(k), i, k, book, false);
  122. sb.append(val); // 所有数据添加到里面,用于判断该行是否为空
  123. obj.put(keyMap.get(k),val);
  124. }
  125. }
  126. if (sb.toString().length() > 0) {
  127. array.add(obj);
  128. }
  129. }
  130. book.close();
  131. return array;
  132. }
  133. /**
  134. * 获取每个单元格的数据
  135. * @param cell 单元格对象
  136. * @param rowNum 第几行
  137. * @param index 该行第几个
  138. * @param book 主要用于关闭流
  139. * @param isKey 是否为键:true-是,false-不是。 如果解析Json键,值为空时报错;如果不是Json键,值为空不报错
  140. * @return
  141. * @throws IOException
  142. */
  143. public String getValue(Cell cell,int rowNum,int index,Workbook book,boolean isKey) throws IOException{
  144. // 空白或空
  145. if (cell == null || cell.getCellType()==Cell.CELL_TYPE_BLANK ) {
  146. if (isKey) {
  147. book.close();
  148. throw new NullPointerException(String.format("the key on row %s index %s is null ", ++rowNum,++index));
  149. }else{
  150. return "";
  151. }
  152. }
  153. // 0. 数字 类型
  154. if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
  155. if (HSSFDateUtil.isCellDateFormatted(cell)) {
  156. Date date = cell.getDateCellValue();
  157. DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  158. return df.format(date);
  159. }
  160. String val = cell.getNumericCellValue()+"";
  161. val = val.toUpperCase();
  162. if (val.contains("E")) {
  163. val = val.split("E")[0].replace(".", "");
  164. }
  165. return val;
  166. }
  167. // 1. String类型
  168. if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
  169. String val = cell.getStringCellValue();
  170. if (val == null || val.trim().length()==0) {
  171. if (book != null) {
  172. book.close();
  173. }
  174. return "";
  175. }
  176. return val.trim();
  177. }
  178. // 2. 公式 CELL_TYPE_FORMULA
  179. if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
  180. return cell.getStringCellValue();
  181. }
  182. // 4. 布尔值 CELL_TYPE_BOOLEAN
  183. if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
  184. return cell.getBooleanCellValue()+"";
  185. }
  186. // 5. 错误 CELL_TYPE_ERROR
  187. return "";
  188. }
  189. }

 

三、单元测试


  这里点出调用封装好的组件时,要用try catch将异常抛出

  1. @RunWith(SpringRunner.class)
  2. @SpringBootTest
  3. public class ExcelTest extends TestCase {
  4. @Autowired
  5. private ExcelResolve excelResolve;
  6. @Test
  7. public void readTest() throws Exception{
  8. File f1 = new File("D:/work/1.xlsx");
  9. try {
  10. System.out.println(excelResolve.readExcel(f1));
  11. } catch (Exception e) {
  12. e.printStackTrace();
  13. }
  14. }
  15. }

 

四、测试结果

 

https://blog.csdn.net/huoji555/article/details/81697968
posted on 2022-03-23 19:52  sunny123456  阅读(1100)  评论(0编辑  收藏  举报