栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java poi导出图片到excel示例代码

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java poi导出图片到excel示例代码

本文实例为大家分享了java使用poi导出图片到Excel的具体代码,供大家参考,具体内容如下

代码实现

Controller


@RequestMapping("/exportData")
public void exportData(Integer talent_type, HttpServletResponse response) {
  String fileId = UUID.randomUUID().toString().replace("-", "");
  Map param = new HashMap<>() ;
  param.put("talent_type", talent_type) ;
  try {
   List> 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> 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 map = (Map) 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示例代码解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对考高分网网站的支持!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/138793.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号