java poi方式的excel的 匯入匯出demo
阿新 • • 發佈:2019-01-09
由於專案中實際的程式碼比較複雜,這裡就參考下簡單版的匯入匯出函式
-
匯出excel檔案
其中
response : 響應物件,用於直接返回給瀏覽器。
list: 內容資料,遍歷填充單元格。
filename: 檔名。
title: excel第一行的標題陣列。
public void exportXml2007(HttpServletResponse response, List<List<Object>> list,String filename,String[] title){ String[] header = title; /***生成Excel***/ // 第一步,建立一個workbook,對應一個Excel檔案 XSSFWorkbook wb = new XSSFWorkbook(); // 第二步,在workbook中新增一個sheet,對應Excel檔案中的sheet XSSFSheet sheet = wb.createSheet(filename); // 第三步,在sheet中新增表頭第0行 XSSFRow row = sheet.createRow((int) 0); // 第四步,建立單元格,並設定 字型相關配置 XSSFCellStyle style = wb.createCellStyle(); XSSFFont font = wb.createFont(); font.setFontHeightInPoints((short) 11); font.setFontName("宋體"); font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); style.setAlignment(HSSFCellStyle.ALIGN_CENTER); style.setFillForegroundColor(HSSFColor.GREY_80_PERCENT.index); style.setFont(font); //依次0行中在新增cell,並設定對應欄位名 XSSFCell cell = null; for(int i=0;i<header.length;i++){ cell = row.createCell((short) i); cell.setCellValue(header[i]); cell.setCellStyle(style); } if(list == null){ return; } for (int i = 0; i < list.size(); i++) { row = sheet.createRow((int) i + 1); //依次從clist中讀取相關資料,並寫入excel List<Object> clist = list.get(i); for(int n=0;n<clist.size();n++) { Object value = clist.get(n); if(value instanceof Date){ row.createCell((short)n).setCellValue(fmt.format(value)); }else{ row.createCell((short)n).setCellValue(clist.get(n).toString()); } } } try { //設定檔案內容下載方式 response.setContentType("application/force-download"); response.setHeader("Content-Disposition", "attachment;filename=\"" + java.net.URLEncoder.encode(filename, "UTF-8") + ".xlsx" + "\" "); wb.write(response.getOutputStream()); response.getOutputStream().close(); } catch (Exception e) { e.printStackTrace(); } }
-
匯入excel 檔案
protected void readXls(InputStream is) throws IOException, InvalidFormatException { Workbook hssfWorkbook = WorkbookFactory.create(is); for (int numSheet = 0; numSheet < hssfWorkbook.getNumberOfSheets(); numSheet++) { Sheet hssfSheet = hssfWorkbook.getSheetAt(numSheet); if (hssfSheet == null) { continue; } for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) { Row hssfRow = hssfSheet.getRow(rowNum); if (hssfRow != null) { /**已經直接取資料行,無需判定 if(hssfRow.getCell(0) == null ){ continue; }else if(hssfRow.getCell(0).getCellType() == Cell.CELL_TYPE_STRING){ String value = hssfRow.getCell(0).getStringCellValue(); try{ Integer.parseInt(value); }catch(Exception e){ continue; } } */ Map<String, Object> map = new HashMap<String, Object>(); map.put("jgId", getValue(hssfRow.getCell(1))); map.put("name", getValue(hssfRow.getCell(3))); map.put("cardType", getValue(hssfRow.getCell(4)).split("-")[0]); map.put("cardNo", getValue(hssfRow.getCell(5))); map.put("sex", getValue(hssfRow.getCell(6)).split("-")[0]); map.put("birth", getValue(hssfRow.getCell(7))); } } } }