怎么在java中使用poi将图片导出到excel
作者
本篇文章为大家展示了怎么在java中使用poi将图片导出到excel,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。
Controller
@RequestMapping("/exportData") publicvoidexportData(Integertalent_type,HttpServletResponseresponse){ StringfileId=UUID.randomUUID().toString().replace("-",""); Map<String,Object>param=newHashMap<>(); param.put("talent_type",talent_type); try{ List<Map<String,Object>>volunteerMapList=volunteerService.getExportData(param); StringrootPath=SysConfigManager.getInstance().getText("/config/sys/rootPath"); StringfilePath=rootPath+"/"+fileId+".xlsx"; volunteerService.exportData(volunteerMapList,filePath); //下载 FileInputStreaminputStream=null; try{ //设置发送到客户端的响应内容类型 response.reset(); response.setContentLength((int)newFile(filePath).length()); response.setContentType("application/octet-stream"); response.addHeader("Content-Disposition","attachment;filename=\""+URLEncoder.encode("文件名.xlsx","UTF-8")+"\""); //读取本地图片输入流 inputStream=newFileInputStream(filePath); //循环取出流中的数据 byte[]b=newbyte[1024]; intlen; while((len=inputStream.read(b))>0) response.getOutputStream().write(b,0,len); }finally{ if(inputStream!=null){ inputStream.close(); } } logger.debug("导出志愿者/人才数据成功!"); }catch(Exceptione){ e.printStackTrace(); logger.error("导出志愿者/人才数据异常!"); } }
Service
publicvoidexportData(List<Map<String,Object>>volunteerMapList,StringfilePath)throwsException{ 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"}; Filefile=newFile(filePath); if(!file.exists())file.createNewFile(); FileOutputStreamfileOutput=newFileOutputStream(file); XSSFWorkbookworkbook=newXSSFWorkbook(); intsheetSize=volunteerMapList.size()+50; doublesheetNo=Math.ceil(volunteerMapList.size()/sheetSize); StringphotoImgPath=SysConfigManager.getInstance().getText("/config/sys/rootPath"); for(intindex=0;index<=sheetNo;index++){ XSSFSheetsheet=workbook.createSheet(); workbook.setSheetName(index,"人才、志愿者"+index); XSSFRowrow=sheet.createRow(0); sheet.setColumnWidth(0,2048); XSSFCellcell; XSSFCellStylecellStyle=workbook.createCellStyle(); XSSFFontfont=workbook.createFont(); font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD); //居中 cellStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER); //加粗 cellStyle.setFont(font); //创建标题 for(inti=0;i<alias.length;i++){ cell=row.createCell(i); cell.setCellValue(alias[i]); cell.setCellStyle(cellStyle); } intstartNo=index*sheetSize; intendNo=Math.min(startNo+sheetSize,volunteerMapList.size()); cellStyle=workbook.createCellStyle(); //居中 cellStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER); cellStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER); //写入各条记录,每条记录对应excel表中的一行 for(inti=startNo;i<endNo;i++){ introwNum=i+1-startNo; row=sheet.createRow(rowNum); Map<String,Object>map=(Map<String,Object>)volunteerMapList.get(i); for(intj=0;j<keys.length;j++){ cell=row.createCell(j); Stringkey=keys[j]; if(key.equals("photo")){ sheet.addMergedRegion(newCellRangeAddress(i+1,i+1,i+1,i+1)); //头像 FilephotoFile=newFile(photoImgPath+map.get(key)); if(photoFile.exists()){ BufferedImagebufferedImage=ImageIO.read(photoFile); ByteArrayOutputStreambyteArrayOut=newByteArrayOutputStream(); ImageIO.write(bufferedImage,"jpg",byteArrayOut); byte[]data=byteArrayOut.toByteArray(); XSSFDrawingdrawingPatriarch=sheet.createDrawingPatriarch(); XSSFClientAnchoranchor=newXSSFClientAnchor(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); Objectvalue=map.get(key); cell.setCellValue(value==null?"":value.toString()); cell.setCellStyle(cellStyle); } } } //设置列宽 for(inti=1;i<alias.length;i++) sheet.autoSizeColumn(i); //处理中文不能自动调整列宽的问题 this.setSizeColumn(sheet,alias.length); } fileOutput.flush(); workbook.write(fileOutput); fileOutput.close(); } //自适应宽度(中文支持) privatevoidsetSizeColumn(XSSFSheetsheet,intsize){ for(intcolumnNum=0;columnNum<size;columnNum++){ intcolumnWidth=sheet.getColumnWidth(columnNum)/256; for(introwNum=0;rowNum<=sheet.getLastRowNum();rowNum++){ XSSFRowcurrentRow; //当前行未被使用过 if(sheet.getRow(rowNum)==null){ currentRow=sheet.createRow(rowNum); }else{ currentRow=sheet.getRow(rowNum); } if(currentRow.getCell(columnNum)!=null){ XSSFCellcurrentCell=currentRow.getCell(columnNum); if(currentCell.getCellType()==XSSFCell.CELL_TYPE_STRING){ intlength=currentCell.getStringCellValue().getBytes().length; if(columnWidth<length)columnWidth=length; } } } columnWidth=columnWidth*256; sheet.setColumnWidth(columnNum,columnWidth>=65280?6000:columnWidth); } }
上述内容就是怎么在java中使用poi将图片导出到excel,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注恰卡编程网行业资讯频道。
目录
推荐阅读
0 条评论
本站已关闭游客评论,请登录或者注册后再评论吧~