本教程只實現poi簡單的上傳下載功能,如需高級操做請繞行!java
<!--poi start--> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.15</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml-schemas</artifactId> <version>3.15</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.15</version> </dependency> <!--poi end-->
resources目錄下準備一個提供下載的文件:題目批量上傳Excel.xlsweb
poi工具類:spring
package com.rm.framework.util; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; 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.springframework.web.multipart.MultipartFile; /** * excel讀寫工具類 */ public class POIUtil { private static Logger logger = Logger.getLogger(POIUtil.class); private final static String xls = "xls"; private final static String xlsx = "xlsx"; /** * 讀入excel文件,解析後返回 * @param file * @throws IOException */ public static List<String[]> readExcel(MultipartFile file) throws IOException{ //檢查文件 checkFile(file); //得到Workbook工做薄對象 Workbook workbook = getWorkBook(file); //建立返回對象,把每行中的值做爲一個數組,全部行做爲一個集合返回 List<String[]> list = new ArrayList<String[]>(); if(workbook != null){ for(int sheetNum = 0;sheetNum < workbook.getNumberOfSheets();sheetNum++){ //得到當前sheet工做表 Sheet sheet = workbook.getSheetAt(sheetNum); if(sheet == null){ continue; } //得到當前sheet的開始行 int firstRowNum = sheet.getFirstRowNum(); //得到當前sheet的結束行 int lastRowNum = sheet.getLastRowNum(); //循環除了第一行的全部行 for(int rowNum = firstRowNum+1;rowNum <= lastRowNum;rowNum++){ //得到當前行 Row row = sheet.getRow(rowNum); if(row == null){ continue; } //得到當前行的開始列 int firstCellNum = row.getFirstCellNum(); //得到當前行的列數 int lastCellNum = row.getPhysicalNumberOfCells(); String[] cells = new String[row.getPhysicalNumberOfCells()]; //循環當前行 StringBuffer sb = new StringBuffer(); for(int cellNum = firstCellNum; cellNum < lastCellNum;cellNum++){ Cell cell = row.getCell(cellNum); cells[cellNum] = getCellValue(cell); sb.append(cells[cellNum]); } int length = sb.toString().length(); if(length>5){ list.add(cells); }else{ sb.delete(0, sb.length()); } } } // workbook.close(); } return list; } public static void checkFile(MultipartFile file) throws IOException{ //判斷文件是否存在 if(null == file){ logger.error("文件不存在!"); throw new FileNotFoundException("文件不存在!"); } //得到文件名 String fileName = file.getOriginalFilename(); //判斷文件是不是excel文件 if(!fileName.endsWith(xls) && !fileName.endsWith(xlsx)){ logger.error(fileName + "不是excel文件"); throw new IOException(fileName + "不是excel文件"); } } public static Workbook getWorkBook(MultipartFile file) { //得到文件名 String fileName = file.getOriginalFilename(); //建立Workbook工做薄對象,表示整個excel Workbook workbook = null; try { //獲取excel文件的io流 InputStream is = file.getInputStream(); //根據文件後綴名不一樣(xls和xlsx)得到不一樣的Workbook實現類對象 if(fileName.endsWith(xls)){ //2003 workbook = new HSSFWorkbook(is); }else if(fileName.endsWith(xlsx)){ //2007 及2007以上 workbook = new XSSFWorkbook(is); } } catch (IOException e) { logger.info(e.getMessage()); } return workbook; } public static String getCellValue(Cell cell){ String cellValue = ""; if(cell == null){ return cellValue; } //把數字當成String來讀,避免出現1讀成1.0的狀況 if(cell.getCellType() == Cell.CELL_TYPE_NUMERIC){ cell.setCellType(Cell.CELL_TYPE_STRING); } //判斷數據的類型 switch (cell.getCellType()){ case Cell.CELL_TYPE_NUMERIC: //數字 cellValue = String.valueOf(cell.getNumericCellValue()); break; case Cell.CELL_TYPE_STRING: //字符串 cellValue = String.valueOf(cell.getStringCellValue()); break; case Cell.CELL_TYPE_BOOLEAN: //Boolean cellValue = String.valueOf(cell.getBooleanCellValue()); break; case Cell.CELL_TYPE_FORMULA: //公式 cellValue = String.valueOf(cell.getCellFormula()); break; case Cell.CELL_TYPE_BLANK: //空值 cellValue = ""; break; case Cell.CELL_TYPE_ERROR: //故障 cellValue = "非法字符"; break; default: cellValue = "未知類型"; break; } return cellValue; } }
controller:apache
package com.rm.eval.controller; import java.util.Date; import com.rm.eval.entity.EvalQuestion; import com.rm.eval.service.EvalQnQuestionService; import com.rm.framework.controller.BaseController; import com.rm.framework.util.CUID; import com.rm.framework.util.POIUtil; import com.rm.sys.dao.SysUserDao; import com.rm.sys.entity.SysUser; import org.apache.poi.hssf.usermodel.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.*; import java.net.URLEncoder; import java.util.List; @RestController @RequestMapping(value = "/excel") public class ExcelController extends BaseController { @Autowired private SysUserDao sysUserDao; //建立表頭 private void createTitle(HSSFWorkbook workbook, HSSFSheet sheet){ HSSFRow row = sheet.createRow(0); //設置列寬,setColumnWidth的第二個參數要乘以256,這個參數的單位是1/256個字符寬度 sheet.setColumnWidth(1,12*256); sheet.setColumnWidth(3,17*256); //設置爲居中加粗 HSSFCellStyle style = workbook.createCellStyle(); HSSFFont font = workbook.createFont(); font.setBold(true); style.setAlignment(HSSFCellStyle.ALIGN_CENTER); style.setFont(font); HSSFCell cell; cell = row.createCell(0); cell.setCellValue("題目內容"); cell.setCellStyle(style); //題目內容,類型,難度,維度,狀態,備註 cell = row.createCell(1); cell.setCellValue("類型"); cell.setCellStyle(style); cell = row.createCell(2); cell.setCellValue("難度"); cell.setCellStyle(style); cell = row.createCell(3); cell.setCellValue("維度"); cell.setCellStyle(style); cell = row.createCell(4); cell.setCellValue("狀態"); cell.setCellStyle(style); cell = row.createCell(5); cell.setCellValue("備註"); cell.setCellStyle(style); } //生成user表excel @GetMapping(value = "/getUser") public String getUser(HttpServletResponse response) throws Exception{ HSSFWorkbook workbook = new HSSFWorkbook(); HSSFSheet sheet = workbook.createSheet("題目批量上傳"); createTitle(workbook,sheet); // List<SysUser> rows = sysUserService.getAll(); List<SysUser> rows = sysUserDao.findAll(); //設置日期格式 HSSFCellStyle style = workbook.createCellStyle(); style.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm")); //新增數據行,而且設置單元格數據 String fileName = "題目批量上傳Excel.xls"; //生成excel文件 buildExcelFile(fileName, workbook); //瀏覽器下載excel buildExcelDocument(fileName,workbook,response); return "download excel"; } //生成excel文件 protected void buildExcelFile(String filename,HSSFWorkbook workbook) throws Exception{ FileOutputStream fos = new FileOutputStream(filename); workbook.write(fos); fos.flush(); fos.close(); } //瀏覽器下載excel protected void buildExcelDocument(String filename,HSSFWorkbook workbook,HttpServletResponse response) throws Exception{ response.setContentType("application/vnd.ms-excel"); response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(filename, "utf-8")); OutputStream outputStream = response.getOutputStream(); workbook.write(outputStream); outputStream.flush(); outputStream.close(); } /** * 文件下載 */ @ResponseBody @GetMapping(value = "/download") public ResponseEntity<byte[]> download(HttpSession session) { System.out.println("das"); ResponseEntity<byte[]> response = null; try { byte[] body = null; InputStream in=ExcelController.class.getClassLoader().getResourceAsStream("題目批量上傳Excel.xls"); body = new byte[in.available()]; in.read(body); HttpHeaders headers = new HttpHeaders(); String fileName11 = new String("題目批量上傳Excel".getBytes("GB2312"), "ISO_8859_1"); headers.add("Content-Disposition", "attachment;filename=" + fileName11 + ".xls"); HttpStatus statusCode = HttpStatus.OK; response = new ResponseEntity<byte[]>(body, headers, statusCode); return response; } catch (IOException e) { e.printStackTrace(); } return response; } @Autowired private com.rm.eval.service.EvalQuestionService evalQuestionService; /** * 文件上傳 * @param file * @return */ @ResponseBody @RequestMapping(value = "/UploadFile") public String UploadFile(@RequestParam(required=false) MultipartFile file ){ String flag ="0"; try{ List<String[]> list = POIUtil.readExcel(file); //這裏獲得的是一個集合,裏面的每個元素是String[]數組 //TODO service實現方法 System.out.println(list); for (int i=0;i<list.size();i++){ EvalQuestion eval = new EvalQuestion(); eval.setTitle(list.get(i)[0]);//題目 String type= list.get(i)[1]; eval.setType(GetAndSetType(type));//類型 String diffcult= list.get(i)[2]; eval.setDiffcult(GetAndSetDiffcult(diffcult));//難度 eval.setWay(list.get(i)[3]); eval.setStatus("1"); eval.setSort(0); eval.setRemark(list.get(i)[4]); eval.setValidateFlag("Y"); eval.setCreateManId(getCurrentUser().getId()); eval.setCreateMan(getCurrentUser().getName()); eval.setCreateDate(new Date()); eval.setModify_date(new Date()); eval.setCom(getUserCom()); eval.setId(CUID.createUUID("EvalQuestion")); evalQuestionService.save(eval); } } catch(Exception e){ flag = "1"; } return flag; } private String GetAndSetDiffcult(String type) { switch (type){ case "簡單": type="A"; break; case "容易": type="B"; break; case "困難": type="C"; break; case "艱難": type="D"; break; } return type; } private String GetAndSetType(String type){ switch (type){ case "單選題": type="A"; break; case "多選題": type="B"; break; case "排序題": type="C"; break; case "程度題": type="D"; break; case "問答題": type="E"; break; case "矩陣程度題": type="F"; break; case "拽選擇題": type="G"; break; } return type; } }