第一步:寫入maven依賴(3.6是比較穩定的版本,可用於生產環境)
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.6</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.6</version> </dependency>
第二步:將Excl導入工具類加進項目中,開箱即用,內置測試main()方法
import org.apache.poi.hssf.usermodel.HSSFDateUtil; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.File; import java.io.FileInputStream; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; /** * * @ClassName: ImportExcelUtil * @Description: excel 導入數據 * @author JonyChen * @date 2018年8月13日 * @time 上午10:28:48 */ public class ImportExcelUtil { private final static String excel2003L =".xls"; //2003- 版本的excel private final static String excel2007U =".xlsx"; //2007+ 版本的excel /** * 描述:獲取IO流中的數據,組裝成List<List<Object>>對象 * @param file * @return * @throws Exception */ public List<List<Object>> importExcel(File file) throws Exception{ List<List<Object>> list = null; //創建Excel工作薄 Workbook work = this.getWorkbook(file); if(null == work){ throw new Exception("創建Excel工作薄為空!"); } Sheet sheet = null; Row row = null; Cell cell = null; list = new ArrayList<List<Object>>(); //遍歷Excel中所有的sheet for (int i = 0; i <work.getNumberOfSheets(); i++) { sheet = work.getSheetAt(i); if(sheet==null){continue;} //遍歷當前sheet中的所有行 for (int j = sheet.getFirstRowNum(); j <= sheet.getLastRowNum(); j++) { row = sheet.getRow(j); if(row==null||row.getFirstCellNum()==j){continue;} //遍歷所有的列 List<Object> li = new ArrayList<Object>(); for (int y = row.getFirstCellNum(); y <row.getLastCellNum(); y++) { cell = row.getCell(y); li.add(this.getCellValue(cell)); } list.add(li); } } return list; } /** * 描述:根據文件后綴,自適應上傳文件的版本 * @param file * @return * @throws Exception */ public Workbook getWorkbook(File file) throws Exception{ Workbook wb = null; String fileType = file.getName().substring(file.getName().lastIndexOf(".")); if(excel2003L.equals(fileType)){ wb = new HSSFWorkbook(new FileInputStream(file)); //2003- }else if(excel2007U.equals(fileType)){ wb = new XSSFWorkbook(new FileInputStream(file)); //2007+ }else{ throw new Exception("解析的文件格式有誤!"); } return wb; } /** * 描述:對表格中數值進行格式化 * @param cell * @return */ public Object getCellValue(Cell cell){ //用String接收所有返回的值 String value = null; DecimalFormat df = new DecimalFormat("0"); //格式化number String字符 SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd"); //日期格式化 DecimalFormat df2 = new DecimalFormat("0.00"); //格式化數字 switch (cell.getCellType()) { case Cell.CELL_TYPE_STRING: //String類型的數據 value = cell.getStringCellValue(); break; case Cell.CELL_TYPE_NUMERIC: //數值類型(取值用cell.getNumericCellValue() 或cell.getDateCellValue()) if("General".equals(cell.getCellStyle().getDataFormatString())){ value = df.format(cell.getNumericCellValue()); }else if(HSSFDateUtil.isCellDateFormatted(cell)){ value = sdf.format(HSSFDateUtil.getJavaDate(cell.getNumericCellValue())); }else{ value = df2.format(cell.getNumericCellValue()); } break; case Cell.CELL_TYPE_BOOLEAN: //Boolean類型 value = String.valueOf(cell.getBooleanCellValue()); break; case Cell.CELL_TYPE_FORMULA: //表達式類型 value = String.valueOf(cell.getCellFormula()); break; case Cell.CELL_TYPE_ERROR: //異常類型 不知道何時算異常 value=String.valueOf(cell.getErrorCellValue()); break; case Cell.CELL_TYPE_BLANK: //空,不知道何時算空 value = ""; break; default: value = ""; break; } if(value.equals("")||value==null){ value = ""; } if (cell == null) { return ""; } return value; } //讀取excel里的字段 public static void main(String[] args){ ImportExcelUtil importExcelUtil=new ImportExcelUtil(); //excel 導入數據demo File file = new File("C:\\Users\\srt\\Desktop\\signup_category.xls"); List<List<Object>> dataList= null; List<SignupCategory> list=new ArrayList<>(); try { dataList = importExcelUtil.importExcel(file); } catch (Exception e) { e.printStackTrace(); } //數據封裝格式一,將表格中的數據遍歷取出后封裝進對象放進List for (int i = 0; i <dataList.size(); i++) { Object type_id = dataList.get(i).get(0); Object type_name = dataList.get(i).get(1); SignupCategory signupCategory=new SignupCategory(); signupCategory.setTypeId(Integer.parseInt((String)type_id)); signupCategory.setTypeName((String)type_name); list.add(signupCategory); System.out.println("------------------"); System.out.println((String)type_id+":"+(String)type_name); } System.out.println(JsonUtils.toJson(list)); //數據封裝格式二,雙重循環遍歷取出元素 /*for (int i = 0; i < dataList.size(); i++) { for (int j = 0; j < dataList.get(i).size(); j++) { System.out.println(dataList.get(i).get(j)); } System.out.println("------------------"); }*/ } }
第三步:在Controller層進行調用即可
補充:
導入基本流程為:前端頁面提供excl數據摸板下載地址,用戶點擊下載模板excl(其實也就是excl的導出),將模板填寫完畢后然后再上傳至服務器中才調用上面的工具類導入真實數據,上面案例只是將導入的數據取出到控制台進行查看,后期如果有導入數據庫的需求,再進行擴展即可,親測可用,對網上其他教程進行了修正,當前是可用狀態!
