在springmvc專案中使用poi匯入匯出excel
阿新 • • 發佈:2018-12-31
@Override public byte[] exportBrandPeriodSort(List<BrandCompleteInfoEntity> list) throws Exception { ByteArrayOutputStream out = new ByteArrayOutputStream(); // 第一步,建立一個webbook,對應一個Excel檔案 HSSFWorkbook wb = new HSSFWorkbook(); // 第二步,在webbook中新增一個sheet,對應Excel檔案中的sheet HSSFSheet sheet = wb.createSheet("檔期排序表"); // 第三步,在sheet中新增表頭第0行,注意老版本poi對Excel的行數列數有限制short HSSFRow row = sheet.createRow((int) 0); // 第四步,建立單元格,並設定值表頭 設定表頭居中 HSSFCellStyle style = wb.createCellStyle(); style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 建立一個居中格式 //設定表頭 List<String> excelHead = getExcelHead(); HSSFCell cell = null; // excel頭 for (int i = 0; i < excelHead.size(); i++) { cell = row.createCell(i); cell.setCellValue(excelHead.get(i)); cell.setCellStyle(style); } // 第五步,寫入實體資料 實際應用中這些資料從資料庫得到 //List<BrandPeriodSortEntity> list = getBrandPeriodSortDynamicOrder(entity, orderType); BrandCompleteInfoEntity brandCompleteInfo = null; // 拼裝excel內容 for (int i = 0; i < list.size(); i++) { row = sheet.createRow((int) i + 1); brandCompleteInfo = list.get(i); // 建立單元格,並設定值 int j=0; insertCell(row, j++, brandCompleteInfo.getBrandId()); insertCell(row, j++, brandCompleteInfo.getBrandName()); insertCell(row, j++, brandCompleteInfo.getMobileShowFrom()); insertCell(row, j++, brandCompleteInfo.getMobileShowTo()); insertCell(row, j++, brandCompleteInfo.getSellMarkValue()); insertCell(row, j++, brandCompleteInfo.getWarehouse()); insertCell(row, j++, brandCompleteInfo.getSortA1()); insertCell(row, j++, brandCompleteInfo.getSortA2()); insertCell(row, j++, brandCompleteInfo.getSortB()); insertCell(row, j++, brandCompleteInfo.getSortC10()); insertCell(row, j++, brandCompleteInfo.getSortC()); insertCell(row, j++, brandCompleteInfo.getHitA()); insertCell(row, j++, brandCompleteInfo.getHitB()); insertCell(row, j++, brandCompleteInfo.getHitC()); insertCell(row, j++, brandCompleteInfo.getCustomSellType()); insertCell(row, j++, channelInfoMapper.loadChannelNameById(brandCompleteInfo.getChannelId())); insertCell(row, j++, brandCompleteInfo.getChannelId()); } wb.write(out); return out.toByteArray(); } /** * 獲取excel表頭 * * @return */ private List<String> getExcelHead() { List<String> result = new ArrayList<String>(17); result.add("XXXXX"); result.add("XXXXX"); result.add("XXXXX"); result.add("XXXXX"); result.add("XXXXX"); result.add("XXXXX"); result.add("XXXXX"); result.add("XXXXX"); result.add("XXXXX"); result.add("XXXXX"); //。。。。 return result; } private void insertCell(HSSFRow row,int i,Object object){ if(object==null){ row.createCell(i).setCellValue(""); }else{ row.createCell(i).setCellValue(object.toString()); } }