有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!


共 (2) 个答案

  1. # 1 楼答案

    我不认为有像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()从工作表中检索现有的电子表格ML图形

    然后,我们可以使用getShapes()检索表中包含的每个形状

  2. # 2 楼答案

    由于您已经开始使用SS公共接口,您可能希望有一个在两种API中都能工作的解决方案。不幸的是,DrawingPatrich还没有完全普及:

    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();
            }
        }
    }