java 读取excel图片导入(亲测有效)
短信预约 -IT技能 免费直播动态提醒
从excel文件中获取图片(兼容新老版本)
public static Map getPictureFromExcel(File file, int sheetNum) throws EncryptedDocumentException, IOException { //获取图片PictureData集合 String fileName = file.getName(); Workbook workbook = null; if (StringUtil.isEmpty(fileName)) { return null; } FileInputStream fileInputStream = new FileInputStream(file); if (fileName.endsWith("xls")) { //2003 workbook = new HSSFWorkbook(fileInputStream); HSSFSheet sheet = (HSSFSheet) workbook.getSheetAt(sheetNum - 1); Map pictures = getPictures(sheet); return pictures; } else if (fileName.endsWith("xlsx")) { //2007 workbook = new XSSFWorkbook(fileInputStream); XSSFSheet sheet = (XSSFSheet) workbook.getSheetAt(sheetNum - 1); Map pictures = getPictures(sheet); return pictures; } return new HashMap(); }
从sheet页中获取图片及图片位置
public static Map getPictures (HSSFSheet sheet) throws IOException { Map map = new HashMap(); List list = sheet.getDrawingPatriarch().getChildren(); for (HSSFShape shape : list) { if (shape instanceof HSSFPicture) { HSSFPicture picture = (HSSFPicture) shape; HSSFClientAnchor cAnchor = picture.getClientAnchor(); PictureData pdata = picture.getPictureData(); String key = cAnchor.getRow1() + "-" + cAnchor.getCol1(); // 行号-列号 map.put(key, pdata); } } return map; } public static Map getPictures (XSSFSheet sheet) throws IOException { Map map = new HashMap(); List list = sheet.getRelations(); for (POIXMLDocumentPart part : list) { if (part instanceof XSSFDrawing) { XSSFDrawing drawing = (XSSFDrawing) part; List shapes = drawing.getShapes(); for (XSSFShape shape : shapes) { XSSFPicture picture = (XSSFPicture) shape; XSSFClientAnchor anchor = picture.getPreferredSize(); CTMarker marker = anchor.getFrom(); String key = marker.getRow() + "-" + marker.getCol(); map.put(key, picture.getPictureData()); } } } return map; }
main方法-获取excel文件中的图片下载到本地
public static void main(String [] args) throws IOException { File file = new File("C:\\Users\\A\\Desktop\\test.xlsx"); //获取图片数据 Map map = getPictureFromExcel(file, 1); //根据图片行列位置获取图片 PictureData picData = (PictureData)map.get("3"+"-"+14); //后缀名 String extension = picData.suggestFileExtension(); byte[] data = picData.getData(); FileOutputStream out = new FileOutputStream("C:\\Users\\A\\Desktop\\" + "picture." + extension); out.write(data); out.close(); }
遇到问题:图片导入解析报错异常java.lang.ClassCastException: org.apache.poi.xssf.usermodel.
XSSFSimpleShape cannot be cast to org.apache.poi.xssf.usermodel.XSSFPicture问题
解决方法:经过排查,为xslx版本shap对象强转为图片对象报错,添加逻辑首先检验if (shape instanceof XSSFPicture)类型然后再进行强转,问题解决
来源地址:https://blog.csdn.net/qq_47100953/article/details/128921497
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341