从.xls文件中读取图像以及它们的位置参考

时间:2015-09-26 10:05:03

标签: java excel apache-poi

在我的一个项目中,我需要从.xls文件中读取图像。对于每一行,都有一列包含我需要读出的图像。

看起来我可以一起阅读所有图像,但是如何获取每个图像的位置,如列和行号,这样我可以将这些图像与其他数据联系起来?

1 个答案:

答案 0 :(得分:2)

只要形状是图片,就可以使用以下内容:

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) {
  }
 }
}