永远勤奋,永远年轻,永远热烈盈眶

永远勤奋,永远年轻,永远热烈盈眶

【Java代码】——Java实现导出Excel中的图片和数据

前言

最近公司需要做导出Excel中的图片和数据,虽然不是什么新的技术,但是我的业务需要图片和数据对应,而每一行肯定会有数据,但是不一定有图片,这时候就需要考虑如何保证图片和数据是一一对应,图片和数据走的是不同的方式,所以这时候就需要考虑让获取每一行图片的row,在循环row的过程中,判断row相等则取出图片,否则就是当前该数据没有图片!

内容

Control层代码

/**
     * 
     * @param key
     * @param file
     * @param request
     * @param response
     *            void
     * @description 将excel数据导入到数据库中
     * @date 2018年4月10日
     * @author 21
     */
    @RequestMapping("/importExcel")
    @ResponseBody
    public Map<String, Object> importExcel(HttpSession session, @RequestParam("lefile") MultipartFile file,
            HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<>();
        int code = Constants.SUCCESS_CODE;
        String message = Constants.SUCCESS_MGS;
        boolean isExcel2003 = true;
        String basePath = session.getServletContext().getRealPath("/zjk/zjzp/");
        try {
            String filename = file.getOriginalFilename();
            if (isExcel2007(filename)) {
                isExcel2003 = false;
            }
            int count = dataListService.importExcelData(file.getInputStream(), isExcel2003, basePath);
            if (count <= 0) {
                code = Constants.FAILTURE_CODE;
                message = Constants.FAILTURE_MGS;
            }
        } catch (IOException e) {
            code = Constants.FAILTURE_CODE;
            message = Constants.FAILTURE_MGS;
            e.printStackTrace();
        }

        map.put("code", code);
        map.put("message", message);
        return map;

    }
public static boolean isExcel2003(String filepath) {
        return filepath.matches("^.+\\.(?i)(xls)$");
    }

    public static boolean isExcel2007(String filepath)            {
        return filepath.matches("^.+\\.(?i)(xlsx)$");
    }

Service层代码

@Transactional
    public int importExcelData(InputStream is, boolean isExcel2003, String basePath) {
        int count = 0;
        Map<String, PictureData> sheetIndexPicMap = new HashMap<String, PictureData>();
        try {
            Workbook workbook = null;
            Sheet sheet = null;
            if (isExcel2003) {
                workbook = new HSSFWorkbook(is);
                sheet = workbook.getSheetAt(0);
                sheetIndexPicMap = ExcelImageUtil.getSheetPictures03(0, (HSSFSheet) sheet, workbook);
            } else {
                workbook = new XSSFWorkbook(is); // 2007版本之上的
                sheet = workbook.getSheetAt(0);
                sheetIndexPicMap = ExcelImageUtil.getSheetPictures07(0, (XSSFSheet) sheet, workbook);
            }
            List<ZJModel> list = readExcelValue(workbook, sheet, basePath, sheetIndexPicMap);
            // 保存到数据库中
            count = dataListDao.insertZJList(list);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return count;
    }
public List<ZJModel> readExcelValue(Workbook wb, Sheet sheet, String basePath,
            Map<String, PictureData> sheetIndexPicMap) {
        // 得到第一个sheet
        List<ZJModel> zjModels = new ArrayList<ZJModel>();
        try {
            Integer totalCells = 0;
            Integer totalRows = sheet.getPhysicalNumberOfRows();
            if (totalRows > 1 && sheet.getRow(0) != null) {
                totalCells = sheet.getRow(0).getPhysicalNumberOfCells();
            }
            for (int i = 1; i < totalRows; i++) {
                Row row = sheet.getRow(i);
                if (row == null) {
                    continue;
                }
                ZJModel zjModel = new ZJModel();
                String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                zjModel.setId(uuid);
                if (sheetIndexPicMap.get("" + i + "") != null) {// 图片信息
                    String picUuid = UUID.randomUUID().toString().replaceAll("-", "");
                    PictureData pictureData = sheetIndexPicMap.get("" + i + "");
                    byte[] buffer = pictureData.getData();
                    String ext = pictureData.suggestFileExtension();// 获取文件拓展名;
                    FileOutputStream outputStream = new FileOutputStream(basePath + picUuid + "." + ext);
                    outputStream.write(buffer);
                    outputStream.close();
                    zjModel.setZjzp(picUuid + "." + ext);
                }else{
                    zjModel.setZjzp(Constants.DEFAULT_FILE_NAME);//默认图片
                }
                for (int j = 0; j < totalCells; j++) {
                    Cell cell = row.getCell(j);
                    if (cell != null) {
                        switch (j) {
                        case 1:// 专家姓名
                            zjModel.setName(cell.getStringCellValue());
                            zjModel.setYwm(cell.getStringCellValue());
                            break;
                        case 2: //中文译名
                            zjModel.setZwym(cell.getStringCellValue());
                            break;
                        case 3:// 从事领域 //照片
                            break;
                        case 4: //单位
                            zjModel.setDw(cell.getStringCellValue());
                            break;
                        case 5:// 专业 //职务/职称
                            zjModel.setZw(cell.getStringCellValue());
                            break;
                        case 6: //联系方式
                            if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
                                BigDecimal bigDecimal = new BigDecimal(cell.getNumericCellValue());
                                String phone = bigDecimal.toString();
                                zjModel.setPhone(phone);
                            }
                            break;
                        case 7:  //固定电话
                            if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
                                BigDecimal bigDecimal = new BigDecimal(cell.getNumericCellValue());
                                String tel = bigDecimal.toString();
                                zjModel.setTel(tel);
                            }
                            break;
                        case 8:  //传真
                            if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
                                BigDecimal bigDecimal = new BigDecimal(cell.getNumericCellValue());
                                String fax = bigDecimal.toString();
                                zjModel.setFax(fax);
                            }
                            break;
                        case 9: //邮箱
                            zjModel.setEmail(cell.getStringCellValue());
                            break;
                        case 10: //身份证号
                            zjModel.setIdnumber(cell.getStringCellValue());
                            break;
                        case 11: //护照号/及有效证件
                            zjModel.setHz(cell.getStringCellValue());
                            break;
                        case 12: //从事领域
                            zjModel.setCsly(cell.getStringCellValue());
                            break;
                        case 13:  //学历
                            zjModel.setXl(cell.getStringCellValue());
                            break;
                        case 14:  //专业
                            zjModel.setZy(cell.getStringCellValue());
                            break;
                        case 15:  //国籍
                            zjModel.setGj(cell.getStringCellValue());
                            break;
                        case 16:   //性别
                            zjModel.setSex(cell.getStringCellValue() == "男" ? 0 : 1);
                            break;
                        case 17:   //银行卡号
                            zjModel.setYhkh(cell.getStringCellValue());
                            break;
                        case 18:  //开户行
                            zjModel.setKhh(cell.getStringCellValue());
                            break;
                        case 19: //银行代码
                            zjModel.setYhdm(cell.getStringCellValue());
                            break;
                        case 20:  //住址
                            zjModel.setAddress(cell.getStringCellValue());
                            break;
                        case 21:
                            zjModel.setBz(cell.getStringCellValue());
                            break;
                        }

                    }

                }
                zjModels.add(zjModel);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return zjModels;
    }

由于在Excel2003和Excel2007版本获取图片的方法不同,所以抽出来两种方法

public class ExcelImageUtil {
 public static Map<String, PictureData> getSheetPictures03(int sheetNum,HSSFSheet sheet,Workbook workbook){
      Map<String,PictureData> sheetIndexPicMap=new HashMap<String, PictureData>();
      @SuppressWarnings("unchecked")
    List<HSSFPictureData> pictures=(List<HSSFPictureData>) workbook.getAllPictures();
      if(pictures.size()>0){
          for (HSSFShape shape : sheet.getDrawingPatriarch().getChildren()) {
              HSSFClientAnchor anchor=(HSSFClientAnchor) shape.getAnchor();
              if(shape instanceof HSSFPicture){
                  HSSFPicture pic=(HSSFPicture) shape;
                  int pictureIndex=pic.getPictureIndex()-1;
                  HSSFPictureData picData=pictures.get(pictureIndex);
                  String picIndex=String.valueOf(anchor.getRow1());
                  sheetIndexPicMap.put(picIndex, picData);
              }

        }

      }
      return sheetIndexPicMap;
  }


  public static Map<String, PictureData> getSheetPictures07(int sheetNum,XSSFSheet sheet,Workbook workbook){
      Map<String,PictureData> sheetIndexPicMap=new HashMap<String, PictureData>();
      for(POIXMLDocumentPart dr:sheet.getRelations()){
          if(dr instanceof XSSFDrawing){
             XSSFDrawing drawing=(XSSFDrawing) dr;
             List<XSSFShape> shapes=drawing.getShapes();
             for (XSSFShape shape : shapes) {
                XSSFPicture pic=(XSSFPicture) shape;
                XSSFClientAnchor anchor=pic.getPreferredSize();
               CTMarker ctMarker=anchor.getFrom();
                String picIndex=String.valueOf(ctMarker.getRow());
                sheetIndexPicMap.put(picIndex, pic.getPictureData());
            }
          }
      }
      return sheetIndexPicMap;
   }
  }

总结

这也是一次对代码的积累,我相信每一次对代码的总结都会对自己的能力有提升,感谢您的浏览,对于代码有可以改进的进步,请不吝赐教!

阅读更多

扫码向博主提问

去开通我的Chat快问

changyinling520

非学,无以致疑;非问,无以广识
  • 擅长领域:
  • Java
  • Angular
版权声明:欢迎访问,本文为小编原创文章 https://blog.csdn.net/changyinling520/article/details/79955056
个人分类: ------【JAVA基础】
上一篇【java代码】——获取文件大小的三种方式区别
下一篇【CSS实践】——div和table中容纳长文本设置省略值...
想对作者说点什么? 我来说一句

java导出图片excel

2017年10月13日 13KB 下载

没有更多推荐了,返回首页

关闭
关闭