简体   繁体   中英

Read images from .xls file together with the references for their locations

In one of my projects I need to read images from an .xls file. For each row there is a column containing an image which I need to read out.

It looks like I can read all the images together, but how can I also get the position of each image, like column and row numbers, so I can relate those images with other data?

As long as the shapes are pictures, the following is possible:

import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.*;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;

import java.io.FileOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.InputStream;

class GetShapePosition {

 public static void main(String[] args) {
  try {

   InputStream inp = new FileInputStream("workbook.xls");
   Workbook wb = WorkbookFactory.create(inp);

   HSSFSheet sheet = (HSSFSheet)wb.getSheetAt(0);

   HSSFPatriarch dravingPatriarch = sheet.getDrawingPatriarch();

   java.util.List<HSSFShape> shapes = dravingPatriarch.getChildren();

   for (HSSFShape shape : shapes) {
    if (shape instanceof HSSFPicture) {
     HSSFPicture hssfPicture = (HSSFPicture)shape;
     int picIndex = hssfPicture.getPictureIndex();
     String filename = hssfPicture.getFileName();
     int row = hssfPicture.getClientAnchor().getRow1();
     int col = hssfPicture.getClientAnchor().getCol1();
     System.out.println("Picture " + picIndex + " with Filename: " + filename + " is located row: " + row + ", col: " + col);
    }
  }

  } catch (InvalidFormatException ifex) {
  } catch (FileNotFoundException fnfex) {
  } catch (IOException ioex) {
  }
 }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM