poi解析excel 成List
阿新 • • 發佈:2018-12-11
效果:
匯入poi依賴的jar包
我是採用spring mvc,後臺接受一個MultipartFile
這裡的PageData就是HashMap,業務需要所以封裝了一次,大家可以將PageData直接替換成HashMap
直接呼叫該方法就能將excel解析成map集合
/**
* 讀EXCEL檔案,獲取Excel資訊集合
* @param fileName
* @param Mfile
* @param sheetNo 讀取第幾個sheet
* @return
*/
public List<PageData> getExcelInfo(String fileName, MultipartFile Mfile,int sheetNo)
以下是程式碼,只有一個util類,需要用到直接拷進去就行
package com.ycsj.util; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import com.fh.util.PageData; 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.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.commons.CommonsMultipartFile; /** * @author lxj * 讀取excel */ public class ReadExcelUtil { //總行數 private int totalRows = 0; //總條數 private int totalCells = 0; //錯誤資訊接收器 private String errorMsg; //構造方法 public ReadExcelUtil(){ } //獲取總行數 public int getTotalRows() { return totalRows;} //獲取總列數 public int getTotalCells() { return totalCells;} //獲取錯誤資訊 public String getErrorInfo() { return errorMsg; } /** * 驗證EXCEL檔案 * @param filePath * @return */ public boolean validateExcel(String filePath){ if (filePath == null || !(WDWUtil.isExcel2003(filePath) || WDWUtil.isExcel2007(filePath))){ errorMsg = "檔名不是excel格式"; return false; } return true; } /** * 讀EXCEL檔案,獲取Excel資訊集合 * @param fileName * @param Mfile * @param sheetNo 讀取第幾個sheet * @return */ public List<PageData> getExcelInfo(String fileName, MultipartFile Mfile,int sheetNo){ //把spring檔案上傳的MultipartFile轉換成CommonsMultipartFile型別 CommonsMultipartFile cf= (CommonsMultipartFile)Mfile; //獲取本地儲存路徑 // 檢查目錄是否存在 File fileDir = new File("uploadFiles\\temporaryExcel\\"); if(!fileDir.exists()){ fileDir.mkdirs(); } //新建一個臨時檔案 File fileTemp = new File("uploadFiles\\temporaryExcel\\"+new Date().getTime() +fileName); //將上傳的檔案寫入新建的檔案中 try { cf.getFileItem().write(fileTemp); } catch (Exception e) { e.printStackTrace(); } //初始化客戶資訊的集合 List<PageData> pds=new ArrayList<PageData>(); //初始化輸入流 InputStream is = null; try{ //驗證檔名是否合格 if(!validateExcel(fileName)){ return null; } //根據檔名判斷檔案是2003版本還是2007版本 boolean isExcel2003 = true; if(WDWUtil.isExcel2007(fileName)){ isExcel2003 = false; } //根據新建的檔案例項化輸入流 is = new FileInputStream(fileTemp); //根據excel裡面的內容讀取資訊 pds = getExcelInfo(is, isExcel2003,sheetNo); is.close(); }catch(Exception e){ e.printStackTrace(); } finally{ if(is !=null) { try{ is.close(); //刪除臨時檔案 fileTemp.delete(); }catch(IOException e){ is = null; e.printStackTrace(); } } } return pds; } /** * 根據excel裡面的內容讀取客戶資訊 * @param is 輸入流 * @param isExcel2003 excel是2003還是2007版本 * @return * @throws IOException */ public List<PageData> getExcelInfo(InputStream is,boolean isExcel2003,int sheetNo){ List<PageData> pds=null; try{ /** 根據版本選擇建立Workbook的方式 */ Workbook wb = null; //當excel是2003時 if(isExcel2003){ wb = new HSSFWorkbook(is); } else{//當excel是2007時 wb = new XSSFWorkbook(is); } //讀取Excel裡面的資訊 pds=readExcelValue(wb,sheetNo); } catch (IOException e) { e.printStackTrace(); } return pds; } /** * 讀取Excel裡面的資訊 * @param wb * @return */ private List<PageData> readExcelValue(Workbook wb,int sheetNo){ //得到第幾個shell Sheet sheet=wb.getSheetAt(sheetNo-1); //得到Excel的行數 this.totalRows=sheet.getPhysicalNumberOfRows(); //得到Excel的列數(前提是有行數) if(totalRows>=1 && sheet.getRow(0) != null){ this.totalCells=sheet.getRow(0).getPhysicalNumberOfCells(); } //第一行的資料 ArrayList<String> keys = new ArrayList<>(); //獲取第一行的資料 Row row1 = sheet.getRow(0); for (int i = 0; i < totalCells; i++) { Cell cell = row1.getCell(i); String value = cell.getStringCellValue(); keys.add(value); } List<PageData> pds=new ArrayList<PageData>(); PageData pd; //迴圈Excel行數,從第二行開始。標題不入庫 for(int r=1;r<totalRows;r++){ Row row = sheet.getRow(r); if (row == null) continue; pd = new PageData(); //迴圈Excel的列 for(int c = 0; c <this.totalCells; c++){ Cell cell = row.getCell(c); //將列的資訊新增到pageData pd.put(keys.get(c),getStringValueFromCell(cell)); } //新增客戶 pds.add(pd); } return pds; } /** * 讀入excel的內容轉換成字串 * @param cell * @return */ private String getStringValueFromCell(Cell cell) { SimpleDateFormat sFormat = new SimpleDateFormat("yyyy/MM/dd"); DecimalFormat decimalFormat = new DecimalFormat("#.#"); String cellValue = ""; if(cell == null) { return cellValue; } else if(cell.getCellType() == Cell.CELL_TYPE_STRING) { cellValue = cell.getStringCellValue(); } else if(cell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC) { if(HSSFDateUtil.isCellDateFormatted(cell)) { double d = cell.getNumericCellValue(); Date date = HSSFDateUtil.getJavaDate(d); cellValue = sFormat.format(date); } else { cellValue = decimalFormat.format((cell.getNumericCellValue())); } } else if(cell.getCellType() == Cell.CELL_TYPE_BLANK) { cellValue = ""; } else if(cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) { cellValue = String.valueOf(cell.getBooleanCellValue()); } else if(cell.getCellType() == Cell.CELL_TYPE_ERROR) { cellValue = ""; } else if(cell.getCellType() == Cell.CELL_TYPE_FORMULA) { cellValue = cell.getCellFormula().toString(); } return cellValue; } } class WDWUtil { // @描述:是否是2003的excel,返回true是2003 public static boolean isExcel2003(String filePath) { return filePath.matches("^.+\\.(?i)(xls)$"); } //@描述:是否是2007的excel,返回true是2007 public static boolean isExcel2007(String filePath) { return filePath.matches("^.+\\.(?i)(xlsx)$"); } }