Java實現讀取excel中的資料及圖片
阿新 • • 發佈:2021-07-01
一、背景
需要完成excel資料的讀取與落庫
二、實現
Java讀取excel資料:指定某一行,讀取整列的資料
/* 如果是xls格式,使用HSSFWorkbook,HSSFSheet,HSSFRow來進行相關操作 如果是xlsx格式,使用XSSFWorkbook,XSSFSheet,XSSFRow來進行相關操作,目前只支援xlsx */ public static HashMap readExcelData(String filename, Integer row, Integer column,Integer sheet) throws IOException {//用於儲存Exce讀取資料 HashMap<Integer,String> hashMap=new HashMap(); log.info("開始讀取excel資料"); //讀取excel資料 File file = ResourceUtils.getFile(filename); InputStream inputStream = new FileInputStream(file); XSSFWorkbook xssfWorkbook=new XSSFWorkbook(inputStream);//獲取sheet表格,及讀取單元格內容 XSSFSheet xssfSheet=xssfWorkbook.getSheetAt(sheet); //先將獲取的單元格設定為String型別,下面使用getStringCellValue獲取單元格內容 Integer cellIndex = 0; while(cellIndex<=column){ //第一列為空時直接,賦值為空 if (xssfSheet.getRow(row)==null || xssfSheet.getRow(row).getCell(cellIndex)==null){ hashMap.put(cellIndex,""); cellIndex++; continue; } xssfSheet.getRow(row).getCell(cellIndex).setCellType(CellType.STRING); String stringValue=xssfSheet.getRow(row).getCell(cellIndex).getStringCellValue(); hashMap.put(cellIndex,stringValue); cellIndex++; } log.info("readExcelData:{}",hashMap.toString()); return hashMap; }
Java讀取excel圖片:獲取整個excel的圖片,可以按照指定的行和列來定位讀取圖片
/** * 獲取Excel中的圖片 * @param xssfSheet * @return */ public static Map<String, XSSFPictureData> getPictures(XSSFSheet xssfSheet){ Map<String,XSSFPictureData> map=new HashMap<>(); List<XSSFShape> list=xssfSheet.getDrawingPatriarch().getShapes(); for (XSSFShape shape:list){ XSSFPicture picture = (XSSFPicture) shape; XSSFClientAnchor xssfClientAnchor=(XSSFClientAnchor) picture.getAnchor(); XSSFPictureData pdata = picture.getPictureData(); // 行號-列號 String key = xssfClientAnchor.getRow1() + "-" + xssfClientAnchor.getCol1(); log.info("key資料:{}",key); map.put(key, pdata); } return map; }
實際呼叫測試
@Test public void test() throws IOException, UnirestException { String filename="classpath:file/org.xlsx"; File file = ResourceUtils.getFile(filename); InputStream inputStream = new FileInputStream(file); XSSFWorkbook xssfWorkbook=new XSSFWorkbook(inputStream); Map<String, XSSFPictureData> map=getPictures(xssfWorkbook.getSheetAt(0)); String mapKey="3-15";//指定行和列 XSSFPictureData xssfPictureData= map.get(mapKey); byte[] data =xssfPictureData.getData(); FileOutputStream out = new FileOutputStream("/Users/test12.png"); out.write(data); out.close(); } }