您好,登錄后才能下訂單哦!
本篇文章為大家展示了怎么在java中使用poi將圖片導出到excel,內容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。
Controller
@RequestMapping("/exportData") public void exportData(Integer talent_type, HttpServletResponse response) { String fileId = UUID.randomUUID().toString().replace("-", ""); Map<String, Object> param = new HashMap<>() ; param.put("talent_type", talent_type) ; try { List<Map<String, Object>> volunteerMapList = volunteerService.getExportData(param) ; String rootPath = SysConfigManager.getInstance().getText("/config/sys/rootPath"); String filePath = rootPath + "/" + fileId + ".xlsx" ; volunteerService.exportData(volunteerMapList, filePath) ; // 下載 FileInputStream inputStream = null; try{ //設置發送到客戶端的響應內容類型 response.reset(); response.setContentLength((int) new File(filePath).length()); response.setContentType("application/octet-stream"); response.addHeader("Content-Disposition", "attachment; filename=\"" + URLEncoder.encode("文件名.xlsx", "UTF-8")+ "\""); //讀取本地圖片輸入流 inputStream = new FileInputStream(filePath); // 循環取出流中的數據 byte[] b = new byte[1024]; int len; while ((len = inputStream.read(b)) > 0) response.getOutputStream().write(b, 0, len); } finally{ if(inputStream != null){ inputStream.close(); } } logger.debug("導出志愿者/人才數據成功!"); } catch (Exception e) { e.printStackTrace(); logger.error("導出志愿者/人才數據異常!"); } }
Service
public void exportData(List<Map<String, Object>> volunteerMapList, String filePath) throws Exception { String[] alias = {"頭像", "名稱", "個人/團體", "志愿者/人才", "性別", "生日", "手機號", "身份證", "省份", "市", "區/縣", "詳細地址", "郵箱", "政治面貌", "學歷", "民族", "職業", "團隊人數", "藝術特長", "介紹"}; String[] keys = {"photo", "name", "type", "talent_type", "sex", "birth_day", "mobile", "idcard", "province", "city", "county", "address", "email", "political", "education", "nation", "profession", "member_count", "art_spetiality", "content"}; File file = new File(filePath); if (!file.exists()) file.createNewFile(); FileOutputStream fileOutput = new FileOutputStream(file); XSSFWorkbook workbook = new XSSFWorkbook(); int sheetSize = volunteerMapList.size() + 50; double sheetNo = Math.ceil(volunteerMapList.size() / sheetSize); String photoImgPath = SysConfigManager.getInstance().getText("/config/sys/rootPath") ; for (int index = 0; index <= sheetNo; index++) { XSSFSheet sheet = workbook.createSheet(); workbook.setSheetName(index, "人才、志愿者" + index); XSSFRow row = sheet.createRow(0); sheet.setColumnWidth(0, 2048); XSSFCell cell; XSSFCellStyle cellStyle = workbook.createCellStyle(); XSSFFont font = workbook.createFont(); font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD); // 居中 cellStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER); // 加粗 cellStyle.setFont(font); //創建標題 for (int i = 0; i < alias.length; i++) { cell = row.createCell(i); cell.setCellValue(alias[i]); cell.setCellStyle(cellStyle); } int startNo = index * sheetSize; int endNo = Math.min(startNo + sheetSize, volunteerMapList.size()); cellStyle = workbook.createCellStyle(); // 居中 cellStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER); cellStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER); // 寫入各條記錄,每條記錄對應excel表中的一行 for (int i = startNo; i < endNo; i++) { int rowNum = i + 1 - startNo ; row = sheet.createRow(rowNum); Map<String, Object> map = (Map<String, Object>) volunteerMapList.get(i); for (int j = 0; j < keys.length; j++) { cell = row.createCell(j); String key = keys[j] ; if (key.equals("photo")){ sheet.addMergedRegion(new CellRangeAddress(i + 1,i + 1,i + 1,i + 1)) ; // 頭像 File photoFile = new File(photoImgPath + map.get(key)) ; if (photoFile.exists()){ BufferedImage bufferedImage = ImageIO.read(photoFile) ; ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream(); ImageIO.write(bufferedImage, "jpg", byteArrayOut); byte[] data = byteArrayOut.toByteArray(); XSSFDrawing drawingPatriarch = sheet.createDrawingPatriarch(); XSSFClientAnchor anchor = new XSSFClientAnchor(480, 30, 700, 250, (short)0, i + 1, (short) 1, i + 2); drawingPatriarch.createPicture(anchor, workbook.addPicture(data, XSSFWorkbook.PICTURE_TYPE_JPEG)); sheet.setColumnWidth((short)500, (short)500); row.setHeight((short)500); } else { cell.setCellType(XSSFCell.CELL_TYPE_STRING); cell.setCellValue(""); } } else { cell.setCellType(XSSFCell.CELL_TYPE_STRING); Object value = map.get(key); cell.setCellValue(value == null ? "" : value.toString()); cell.setCellStyle(cellStyle); } } } // 設置列寬 for (int i = 1; i < alias.length; i++) sheet.autoSizeColumn(i); // 處理中文不能自動調整列寬的問題 this.setSizeColumn(sheet, alias.length); } fileOutput.flush(); workbook.write(fileOutput); fileOutput.close(); } // 自適應寬度(中文支持) private void setSizeColumn(XSSFSheet sheet, int size) { for (int columnNum = 0; columnNum < size; columnNum++) { int columnWidth = sheet.getColumnWidth(columnNum) / 256; for (int rowNum = 0; rowNum <= sheet.getLastRowNum(); rowNum++) { XSSFRow currentRow; //當前行未被使用過 if (sheet.getRow(rowNum) == null) { currentRow = sheet.createRow(rowNum); } else { currentRow = sheet.getRow(rowNum); } if (currentRow.getCell(columnNum) != null) { XSSFCell currentCell = currentRow.getCell(columnNum); if (currentCell.getCellType() == XSSFCell.CELL_TYPE_STRING) { int length = currentCell.getStringCellValue().getBytes().length; if (columnWidth < length) columnWidth = length; } } } columnWidth = columnWidth * 256 ; sheet.setColumnWidth(columnNum, columnWidth >= 65280 ? 6000 : columnWidth); } }
上述內容就是怎么在java中使用poi將圖片導出到excel,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。