我正在尝试从单张纸张加载图片,但在documentation中,只有示例如何从整个文档加载图片(workbook.getAllPictures();
)
答案 0 :(得分:2)
我认为单个工作表可以使用getAllPictures()
这么简单。一种解决方案是做这样的事情(假设你正在使用XSSF):
public static void main(String[] args) {
try {
InputStream inp = new FileInputStream("workbook.xlsx");
Workbook wb = WorkbookFactory.create(inp);
XSSFSheet sheet1 = (XSSFSheet)wb.getSheetAt(0);
//returns the existing SpreadsheetDrawingML from the sheet, or creates a new one
XSSFDrawing drawing = sheet1.createDrawingPatriarch();
//loop through all of the shapes in the drawing area
for(XSSFShape shape : drawing.getShapes()){
if(shape instanceof Picture){
//convert the shape into a picture
XSSFPicture picture = (XSSFPicture)shape;
//your logic here
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
一般的想法是我们使用createDrawingPatriarch()
从工作表中检索现有的SpreadsheetML绘图。
然后我们可以使用getShapes()
来检索工作表中包含的每个形状。
答案 1 :(得分:1)
由于您已经开始使用SS Common接口,因此您可能希望拥有一个适用于这两种API的解决方案。不幸的是,DrawingPatriach尚未完全SS-Commonized :(
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFPatriarch;
import org.apache.poi.hssf.usermodel.HSSFShape;
import org.apache.poi.ss.usermodel.Drawing;
import org.apache.poi.ss.usermodel.Picture;
import org.apache.poi.ss.usermodel.PictureData;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFDrawing;
import org.apache.poi.xssf.usermodel.XSSFShape;
public class XlsPictures {
public static void main(String args[]) throws Exception {
Workbook wb = WorkbookFactory.create(new File("picture.xls"));
Sheet sh = wb.getSheetAt(0);
Drawing draw = sh.createDrawingPatriarch();
List<Picture> pics = new ArrayList<Picture>();
if (draw instanceof HSSFPatriarch) {
HSSFPatriarch hp = (HSSFPatriarch)draw;
for (HSSFShape hs : hp.getChildren()) {
if (hs instanceof Picture) {
pics.add((Picture)hs);
}
}
} else {
XSSFDrawing xdraw = (XSSFDrawing)draw;
for (XSSFShape xs : xdraw.getShapes()) {
if (xs instanceof Picture) {
pics.add((Picture)xs);
}
}
}
for (Picture p : pics) {
PictureData pd = p.getPictureData();
byte saveme[] = pd.getData();
}
}
}