1、pom.xml引入jarhtml
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-contrib</artifactId> <version>3.6</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml-schemas</artifactId> <version>3.7</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.7</version> </dependency>
2、編寫工具類java
package com.zdnst.common.infra.utils; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import com.ctc.wstx.sw.EncodingXmlWriter; import com.zdnst.common.infra.constants.BaseCode; import com.zdnst.common.infra.exception.ZdnstException; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; 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 org.apache.xmlbeans.impl.piccolo.io.FileFormatException; import javax.servlet.http.HttpServletRequest; /** * Created by yongqin.zhong on 2017-11-14. */ public class ExcelReader { private static final String EXTENSION_XLS = "xls"; private static final String EXTENSION_XLSX = "xlsx"; /** * 通用讀取excel * @param request * @return 返回LinkedHashMap 的list,第一行是key,其他是value * @throws ZdnstException */ public static List<Map> readCommonExcel(HttpServletRequest request) throws ZdnstException { List<Map> resultList = new ArrayList<Map>(); Workbook workbook=ExcelReader.getOneExcelWorkBook(request); try { for(int sheet=0;sheet<workbook.getNumberOfSheets();sheet++){ // 獲取第sheet張Sheet表 Sheet rs = workbook.getSheetAt(sheet); int rowCount = rs.getPhysicalNumberOfRows(); //獲取總行數 if (rowCount == 0) { // 導入數據表爲空直接跳過 continue; } //獲取標題,檢查列數 int totalCellInt = rs.getRow(0).getPhysicalNumberOfCells();//獲取總列數 for (int row = 1; row < rowCount; row++) {//跳過第一行標題 Map<String, Object> map = new LinkedHashMap<>(); for(int cellInt=0;cellInt<totalCellInt;cellInt++){ String noOneCellValue=getCellValue( rs.getRow(0).getCell(cellInt),true);//讀取第一行標題爲key String curCellValue=getCellValue( rs.getRow(row).getCell(cellInt),true);//讀取第一行標題爲key if(StringUtils.isNotEmpty(noOneCellValue)) map.put(noOneCellValue,curCellValue); } resultList.add(map); } } } catch (ZdnstException e) { throw new ZdnstException(e.getCode(),e); } catch (Exception e) { throw new ZdnstException(BaseCode.ERROR_CODE110,e); } return resultList; } /** * 讀取excel文件內容 * @param request * @throws FileNotFoundException * @throws FileFormatException */ public static Workbook getOneExcelWorkBook(HttpServletRequest request) throws ZdnstException{ Workbook workbook =null; File tempFile=null; try { String fileType = SystemProperties.getProperties().getProperty( "fileType"); // 得到磁盤文件條目工廠 DiskFileItemFactory factory = new DiskFileItemFactory(); // 獲取文件須要上傳到的路徑 String path = request.getSession().getServletContext() .getRealPath("/files"); // 若是沒如下兩行設置的話,上傳大的 文件 會佔用 不少內存, // 設置暫時存放的 存儲室 , 這個存儲室,能夠和 最終存儲文件 的目錄不一樣 factory.setRepository(new File(path)); // factory.s.setSizeMax(2*1024*1024); // 設置 緩存的大小,當上傳文件的容量超過該緩存時,直接放到 暫時存儲室 factory.setSizeThreshold(1024 * 1024 * 10);// 10M緩存大小 ServletFileUpload upload = new ServletFileUpload(factory); // 能夠上傳多個文件 List<FileItem> list = (List<FileItem>) upload.parseRequest(request); if(list!=null&&list.size()>0) { FileItem item = list.get(0); String value = item.getName(); if (CommonUtils.isNotEmpty(value)) { String filePath=path+"/"+value; tempFile=new File(filePath); item.write(tempFile); // 檢查 preReadCheck(filePath); workbook = getWorkbook(filePath); } } } catch (Exception e) { e.printStackTrace(); throw new ZdnstException(BaseCode.ERROR_CODE200,"文件格式不正確"); }finally { if(tempFile!=null){ try{ tempFile.delete(); } catch (Exception e) { e.printStackTrace(); } } } return workbook; } /*** * <pre> * 取得Workbook對象(xls和xlsx對象不一樣,不過都是Workbook的實現類) * xls:HSSFWorkbook * xlsx:XSSFWorkbook * @param filePath * @return * @throws IOException * </pre> */ private static Workbook getWorkbook(String filePath) throws IOException { Workbook workbook = null; InputStream is = new FileInputStream(filePath); if (filePath.endsWith(EXTENSION_XLS)) { workbook = new HSSFWorkbook(is); } else if (filePath.endsWith(EXTENSION_XLSX)) { workbook = new XSSFWorkbook(is); } return workbook; } /** * 文件檢查 * @param filePath * @throws FileNotFoundException * @throws FileFormatException */ private static void preReadCheck(String filePath) throws FileNotFoundException, FileFormatException { // 常規檢查 File file = new File(filePath); if (!file.exists()) { throw new FileNotFoundException("傳入的文件不存在:" + filePath); } if (!(filePath.endsWith(EXTENSION_XLS) || filePath.endsWith(EXTENSION_XLSX))) { throw new FileFormatException("傳入的文件不是excel"); } } /** * 取單元格的值 * @param cell 單元格對象 * @param treatAsStr 爲true時,當作文原本取值 (取到的是文本,不會把「1」取成「1.0」) * @return */ private static String getCellValue(Cell cell, boolean treatAsStr) { if (cell == null) { return ""; } if (treatAsStr) { // 雖然excel中設置的都是文本,可是數字文本還被讀錯,如「1」取成「1.0」 // 加上下面這句,臨時把它當作文原本讀取 cell.setCellType(Cell.CELL_TYPE_STRING); } if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) { return String.valueOf(cell.getBooleanCellValue()); } else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) { return String.valueOf(cell.getNumericCellValue()); } else { return String.valueOf(cell.getStringCellValue()); } } }
3、編寫control方法apache
/** * 通用讀取excel * @param request * @param response * @return */ @RequestMapping(value = "/readCommonExcel", method = RequestMethod.POST) public ModelAndView readCommonExcel(HttpServletRequest request,HttpServletResponse response) throws Exception{ try { List<Map> dataMap = ExcelReader.readCommonExcel(request); return JsonView.dataToJson(dataMap, response); } catch (ZdnstException e) { //打印異常消息 logger.error(Constants.EX_CONTROLLER_EXCEPTION + BaseCode.getDetailMsg(e)); //返回異常消息 return JsonView.addErrorToJson(e, response, null); } catch (Exception e) { //轉換異常 ZdnstException ex = BaseCode.getZdnstException(e); //打印詳細信息 logger.error(Constants.EX_CONTROLLER_EXCEPTION + BaseCode.getDetailMsg(ex),e); //返回異常消息 return JsonView.addErrorToJson(ex, response, null); } }
4、編寫jsp,調試範例緩存
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>上傳附件</title> </head> <body> <!-- 添加、編輯框開始 --> <div> <form id="myForm" method="post" action="/jsf/excel/readCommonExcel" enctype="multipart/form-data" > <table> <tr> <td align="right"><span>上傳封面:</span></td> <td><input name="186bdc97-8426-11e5-a5bd-000c294debb1" type="file"> <input type="submit" name="submit" value="save"/> </td> </tr> </table> </form> </div> <!-- 添加框結束 --> </body> </html>