2019獨角獸企業重金招聘Python工程師標準>>>
最近項目采用jfinal的項目要對一些excel進行操作,經過考慮采用jfinal+poi,在一些學習,使用后總結并分享一些代碼片段。
導入excel========================================
protected Workbook workbook =null;protected File file=null;public Object readExcel(UploadFile uploadFile) throws Exception{String path = uploadFile.getUploadPath() + "/" + System.currentTimeMillis() + uploadFile.getFileName();file = new File(path);uploadFile.getFile().renameTo(file);//文件是否存在this.fileCheck(path);//返回workbookworkbook=this.getWorkbook(path);if (validateData()){//解析excel讀取數據,并返回List<Record>List<Record> list = new ArrayList<>();String itemName =null;Date startTime = null;sheet = workbook.getSheetAt(0);int rows = sheet.getLastRowNum();//從0到最后一行非空rowfor (int i = 3; i <= rows; i++) {Row row = sheet.getRow(i);if (row != null) {int cells = row.getLastCellNum();//行中,從0到最后一個非空cellfor (int j = 0; j < cells; j++) {Cell cell = row.getCell(j);if (cell != null) {// 需驗證單元格里面的數據,""也會返回nullswitch (j) {case 0:cell.setCellType(Cell.CELL_TYPE_STRING);itemName= cell.getStringCellValue().trim();break;case 1:if(cell.getCellType()==HSSFCell.CELL_TYPE_NUMERIC && DateUtil.isCellDateFormatted(cell)){//日期也是數值類型startTime = cell.getDateCellValue();}else{throw new Exception("請輸入正確的日期!");}break;default:break;}}Record r = new Record();r.set("itemName", itemName);r.set("startTime", startTime);list.add(r);itemName=null;startTime=null;}workbook.close();file.delete();return list;}return null;};/*** 文件常規檢查* @param filePath* @throws FileNotFoundException* @throws FileFormatException*/protected void fileCheck(String filePath) throws FileNotFoundException, FileFormatException {File file = new File(filePath);if (!file.exists()) {throw new FileNotFoundException("傳入的文件不存在:" + filePath);}//03 ,07if (!(filePath.endsWith(".xls") || filePath.endsWith(".xlsx"))) {throw new FileFormatException("傳入的文件不是excel");}}/*** 03或07excel**/protected Workbook getWorkbook(String filePath) throws IOException {Workbook workbook = null;InputStream is = new FileInputStream(filePath);if (filePath.endsWith(".xls")) {workbook = new HSSFWorkbook(is);} else if (filePath.endsWith(".xlsx")) {workbook = new XSSFWorkbook(is);}return workbook;}
導出excel數據===========================================
protected HSSFWorkbook workbook = new HSSFWorkbook();protected HSSFSheet sheet=workbook.createSheet();;protected HSSFRow row;protected HSSFCell cell;protected HSSFCellStyle style ;protected HSSFFont font ;protected List<Record> list;protected String[] headersId;protected String[] headersName;protected String title;protected String fileName;//以流的形式直接輸出excel到客戶端,在controller調用此方法后再次調用 renderNull()此方法即可。
//網上有的是生成excel file 再用renderFile()的方法輸出到客戶端,但我沒有采用這種方法。(注意:這種應該在文件輸出后將文件刪除)
public void writeExcel(List<Record> list,String title,String[] headersId,String[] headersName,String fileName,HttpServletResponse response) throws Exception{this.list=list;this.title=title;this.fileName=fileName;this.headersId=headersId;this.headersName=headersName;this.genTitle();this.genList();this.genFooter();OutputStream outputStream=response.getOutputStream();try {response.setContentType("application/vnd.ms-excel");response.setCharacterEncoding("utf-8");response.setHeader("Content-Disposition","attachment;filename="+URLEncoder.encode(fileName, "utf-8")+".xls");workbook.write(outputStream);outputStream.flush();}catch (Exception e) {throw new Exception("導出失敗!");}finally {outputStream.close();workbook.close();}}//生成title及標題行public void genTitle(){row = sheet.createRow(0);//題頭sheet.addMergedRegion(new CellRangeAddress(0, 2, 0, headersName.length-1));cell = row.createCell(0);cell.setCellStyle(genTitleStyle());cell.setCellValue(title);rowindex+=3;}//生成list數據public void genList(){//表格標題行row = sheet.createRow(rowindex);for(int i=0;i<headersName.length;i++){cell = row.createCell(i);cell.setCellStyle(genH2Style());cell.setCellValue(headersName[i]);}Record r=null;for(int i=0;i<list.size();i++){rowindex++;row = sheet.createRow(rowindex);r = list.get(i);//每行數據for(int j =0;j<headersId.length;j++){cell = row.createCell(j);if(r.get(headersId[j]) instanceof Date)cell.setCellValue(DateUtil.dateToStr((Date)r.get(headersId[j]), "yyyy-MM-dd"));else if(r.get(headersId[j]) instanceof String)cell.setCellValue((String)r.get(headersId[j])==null?"":(String)r.get(headersId[j]));else if(r.get(headersId[j]) instanceof Number)cell.setCellValue(r.get(headersId[j])==null?"":String.valueOf(r.get(headersId[j])));}}rowindex++;}
?
?
?
?