org.apache.poi.hssf.usermodel.HSSFClientAnchor Java Examples

The following examples show how to use org.apache.poi.hssf.usermodel.HSSFClientAnchor. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PoiPublicUtil.java    From autopoi with Apache License 2.0 6 votes vote down vote up
/**
 * 获取Excel2003图片
 * 
 * @param sheet
 *            当前sheet对象
 * @param workbook
 *            工作簿对象
 * @return Map key:图片单元格索引(1_1)String,value:图片流PictureData
 */
public static Map<String, PictureData> getSheetPictrues03(HSSFSheet sheet, HSSFWorkbook workbook) {
	Map<String, PictureData> sheetIndexPicMap = new HashMap<String, PictureData>();
	List<HSSFPictureData> pictures = workbook.getAllPictures();
	if (!pictures.isEmpty()) {
		for (HSSFShape shape : sheet.getDrawingPatriarch().getChildren()) {
			HSSFClientAnchor anchor = (HSSFClientAnchor) shape.getAnchor();
			if (shape instanceof HSSFPicture) {
				HSSFPicture pic = (HSSFPicture) shape;
				int pictureIndex = pic.getPictureIndex() - 1;
				HSSFPictureData picData = pictures.get(pictureIndex);
				String picIndex = String.valueOf(anchor.getRow1()) + "_" + String.valueOf(anchor.getCol1());
				sheetIndexPicMap.put(picIndex, picData);
			}
		}
		return sheetIndexPicMap;
	} else {
		return null;
	}
}
 
Example #2
Source File: PoiPublicUtil.java    From jeasypoi with Apache License 2.0 6 votes vote down vote up
/**
 * 获取Excel2003图片
 * 
 * @param sheet
 *            当前sheet对象
 * @param workbook
 *            工作簿对象
 * @return Map key:图片单元格索引(1_1)String,value:图片流PictureData
 */
public static Map<String, PictureData> getSheetPictrues03(HSSFSheet sheet, HSSFWorkbook workbook) {
	Map<String, PictureData> sheetIndexPicMap = new HashMap<String, PictureData>();
	List<HSSFPictureData> pictures = workbook.getAllPictures();
	if (!pictures.isEmpty()) {
		for (HSSFShape shape : sheet.getDrawingPatriarch().getChildren()) {
			HSSFClientAnchor anchor = (HSSFClientAnchor) shape.getAnchor();
			if (shape instanceof HSSFPicture) {
				HSSFPicture pic = (HSSFPicture) shape;
				int pictureIndex = pic.getPictureIndex() - 1;
				HSSFPictureData picData = pictures.get(pictureIndex);
				String picIndex = String.valueOf(anchor.getRow1()) + "_" + String.valueOf(anchor.getCol1());
				sheetIndexPicMap.put(picIndex, picData);
			}
		}
		return sheetIndexPicMap;
	} else {
		return null;
	}
}
 
Example #3
Source File: PoiPublicUtil.java    From easypoi with Apache License 2.0 6 votes vote down vote up
/**
 * 获取Excel2003图片
 * 
 * @param sheet
 *            当前sheet对象
 * @param workbook
 *            工作簿对象
 * @return Map key:图片单元格索引(1_1)String,value:图片流PictureData
 */
public static Map<String, PictureData> getSheetPictrues03(HSSFSheet sheet, HSSFWorkbook workbook) {
    Map<String, PictureData> sheetIndexPicMap = new HashMap<String, PictureData>();
    List<HSSFPictureData> pictures = workbook.getAllPictures();
    if (!pictures.isEmpty()) {
        for (HSSFShape shape : sheet.getDrawingPatriarch().getChildren()) {
            HSSFClientAnchor anchor = (HSSFClientAnchor) shape.getAnchor();
            if (shape instanceof HSSFPicture) {
                HSSFPicture pic = (HSSFPicture) shape;
                int pictureIndex = pic.getPictureIndex() - 1;
                HSSFPictureData picData = pictures.get(pictureIndex);
                String picIndex = String.valueOf(anchor.getRow1()) + "_"
                                  + String.valueOf(anchor.getCol1());
                sheetIndexPicMap.put(picIndex, picData);
            }
        }
        return sheetIndexPicMap;
    } else {
        return null;
    }
}
 
Example #4
Source File: ExcelPublicUtil.java    From jeewx with Apache License 2.0 6 votes vote down vote up
/** 
    * 获取Excel2003图片 
    * @param sheet 当前sheet对象 
    * @param workbook 工作簿对象 
    * @return Map key:图片单元格索引(1_1)String,value:图片流PictureData 
    */  
   @SuppressWarnings("unchecked")
public static Map<String, PictureData> getSheetPictrues03(HSSFSheet sheet, 
   		HSSFWorkbook workbook) {  
       Map<String, PictureData> sheetIndexPicMap = new HashMap<String, PictureData>(); 
       List<HSSFPictureData> pictures = workbook.getAllPictures();  
       if (pictures.size() != 0) {  
           for (HSSFShape shape : sheet.getDrawingPatriarch().getChildren()) {  
               HSSFClientAnchor anchor = (HSSFClientAnchor) shape.getAnchor();  
               if (shape instanceof HSSFPicture) {  
                   HSSFPicture pic = (HSSFPicture) shape;  
                   int pictureIndex = pic.getPictureIndex() - 1;  
                   HSSFPictureData picData = pictures.get(pictureIndex);  
                   String picIndex = String.valueOf(anchor.getRow1()) + "_"  
                           + String.valueOf(anchor.getCol1());  
                   sheetIndexPicMap.put(picIndex, picData);  
               }
           }  
           return sheetIndexPicMap;  
       } else {  
           return (Map<String, PictureData>) sheetIndexPicMap.put(null, null);  
       }  
   }
 
Example #5
Source File: XLSPrinter.java    From unitime with Apache License 2.0 6 votes vote down vote up
protected void addImageToSheet(int colNumber, int rowNumber, HSSFSheet sheet, BufferedImage image, double reqImageWidthMM, double reqImageHeightMM, int resizeBehaviour) throws IOException {
      ClientAnchorDetail colClientAnchorDetail = fitImageToColumns(sheet, colNumber, reqImageWidthMM, resizeBehaviour);
      ClientAnchorDetail rowClientAnchorDetail = fitImageToRows(sheet, rowNumber, reqImageHeightMM, resizeBehaviour);

      HSSFClientAnchor anchor = new HSSFClientAnchor(0,
                                    0,
                                    colClientAnchorDetail.getInset(),
                                    rowClientAnchorDetail.getInset(),
                                    (short)colClientAnchorDetail.getFromIndex(),
                                    rowClientAnchorDetail.getFromIndex(),
                                    (short)colClientAnchorDetail.getToIndex(),
                                    rowClientAnchorDetail.getToIndex());

      anchor.setAnchorType(AnchorType.MOVE_AND_RESIZE);
      
      ByteArrayOutputStream bytes = new ByteArrayOutputStream();
ImageIO.write(image, "PNG", bytes);

      int index = sheet.getWorkbook().addPicture(bytes.toByteArray(), HSSFWorkbook.PICTURE_TYPE_PNG);

      HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
      patriarch.createPicture(anchor, index);
  }
 
Example #6
Source File: POIImage.java    From excel2pdf with Apache License 2.0 5 votes vote down vote up
public POIImage getCellImage(Cell cell) {
    Sheet sheet = cell.getSheet();
    if (sheet instanceof HSSFSheet) {
        HSSFSheet hssfSheet = (HSSFSheet) sheet;
        if (hssfSheet.getDrawingPatriarch() != null) {
            List<HSSFShape> shapes = hssfSheet.getDrawingPatriarch().getChildren();
            for (HSSFShape shape : shapes) {
                HSSFClientAnchor anchor = (HSSFClientAnchor) shape.getAnchor();
                if (shape instanceof HSSFPicture) {
                    HSSFPicture pic = (HSSFPicture) shape;
                    PictureData data = pic.getPictureData();
                    String extension = data.suggestFileExtension();
                    int row1 = anchor.getRow1();
                    int row2 = anchor.getRow2();
                    int col1 = anchor.getCol1();
                    int col2 = anchor.getCol2();
                    if (row1 == cell.getRowIndex() && col1 == cell.getColumnIndex()) {
                        dimension = pic.getImageDimension();
                        this.anchor = anchor;
                        this.bytes = data.getData();
                    }
                }
            }
        }
    }
    return this;
}
 
Example #7
Source File: DefaultExcelView.java    From Mario with Apache License 2.0 5 votes vote down vote up
/**
 * 构建excel的表头
 * 
 * @param filename
 * @param headerList
 */
private void buildExcelHead(String filename, HSSFWorkbook workbook) {
    // Initialize
    List<String> headerList = Lists.newArrayList();
    for (Object[] os : annotationList) {
        String t = ((ExcelField) os[0]).title();
        headerList.add(t);
    }

    sheet = workbook.createSheet("导出数据");

    // Create header
    Row headerRow = sheet.createRow(rownum++);
    headerRow.setHeightInPoints(16);
    for (int i = 0; i < headerList.size(); i++) {
        Cell cell = headerRow.createCell(i);
        String[] ss = StringUtils.split(headerList.get(i), "**", 2);
        if (ss.length == 2) {
            cell.setCellValue(ss[0]);
            Comment comment = sheet.createDrawingPatriarch().createCellComment(
                    new HSSFClientAnchor(0, 0, 0, 0, (short) 3, 3, (short) 5, 6));
            comment.setString(new XSSFRichTextString(ss[1]));
            cell.setCellComment(comment);
        } else {
            cell.setCellValue(headerList.get(i));
        }
        sheet.autoSizeColumn(i);
    }
    for (int i = 0; i < headerList.size(); i++) {
        int colWidth = sheet.getColumnWidth(i) * 2;
        sheet.setColumnWidth(i, colWidth < 3000 ? 3000 : colWidth);
    }
}
 
Example #8
Source File: HSSFPicturesHelper.java    From yarg with Apache License 2.0 5 votes vote down vote up
public static List<HSSFClientAnchor> getAllAnchors(EscherAggregate escherAggregate) {
    List<HSSFClientAnchor> pictures = new ArrayList<HSSFClientAnchor>();
    if (escherAggregate == null) return Collections.emptyList();
    List<EscherRecord> escherRecords = escherAggregate.getEscherRecords();
    searchForAnchors(escherRecords, pictures);
    return pictures;
}
 
Example #9
Source File: ImageUtils.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Calculates the dimensions in EMUs for the anchor of the given picture
 *
 * @param picture the picture containing the anchor
 * @return the dimensions in EMUs
 */
public static Dimension getDimensionFromAnchor(Picture picture) {
    ClientAnchor anchor = picture.getClientAnchor();
    boolean isHSSF = (anchor instanceof HSSFClientAnchor);
    Sheet sheet = picture.getSheet();

    double w = 0;
    int col2 = anchor.getCol1();

    //space in the leftmost cell
    w = sheet.getColumnWidthInPixels(col2++);
    if (isHSSF) {
        w *= 1 - anchor.getDx1()/1024d;
    } else {
        w -= anchor.getDx1()/(double)EMU_PER_PIXEL;
    }
    
    while(col2 < anchor.getCol2()){
        w += sheet.getColumnWidthInPixels(col2++);
    }
    
    if (isHSSF) {
        w += sheet.getColumnWidthInPixels(col2) * anchor.getDx2()/1024d;
    } else {
        w += anchor.getDx2()/(double)EMU_PER_PIXEL;
    }

    double h = 0;
    int row2 = anchor.getRow1();
    
    h = getRowHeightInPixels(sheet,row2++);
    if (isHSSF) {
        h *= 1 - anchor.getDy1()/256d;
    } else {
        h -= anchor.getDy1()/(double)EMU_PER_PIXEL;
    }

    while(row2 < anchor.getRow2()){
        h += getRowHeightInPixels(sheet,row2++);
    }
    
    if (isHSSF) {
        h += getRowHeightInPixels(sheet,row2) * anchor.getDy2()/256;
    } else {
        h += anchor.getDy2()/(double)EMU_PER_PIXEL;
    }

    w *= EMU_PER_PIXEL;
    h *= EMU_PER_PIXEL;
    
    return new Dimension((int)Math.rint(w), (int)Math.rint(h));
}
 
Example #10
Source File: JRXlsMetadataExporter.java    From jasperreports with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
protected void writeCurrentRow(Map<String, Object> currentRow, Map<String, Object> repeatedValues)  throws JRException {
	row = sheet.createRow(sheet.getPhysicalNumberOfRows());
	setRowHeight(row);
	
	for(int i = 0; i< columnNames.size(); i++) {
		String columnName = columnNames.get(i);
		CellSettings cellSettings = (CellSettings)currentRow.get(columnName) == null 
			? (repeatedValues.get(columnName) != null 
			? (CellSettings)repeatedValues.get(columnName)
			: null)
			: (CellSettings)currentRow.get(columnName);
		cell = row.createCell(i);
		if(cellSettings != null) {
			CellType type = cellSettings.getCellType();
			cell.setCellType(type);
			Object cellValue = cellSettings.getCellValue();
			if(cellValue != null) {
				if(cellValue instanceof RichTextString) {
					cell.setCellValue((RichTextString)cellSettings.getCellValue());
				} else if (cellValue instanceof Number) {
					cell.setCellValue(((Number)cellSettings.getCellValue()).doubleValue());
				} else if (cellValue instanceof Date) {
					cell.setCellValue((Date)cellSettings.getCellValue());
				} else if(cellValue instanceof Boolean) {
					cell.setCellValue((Boolean)cellSettings.getCellValue());
				}else if(cellValue instanceof ImageSettings){
					ImageSettings imageSettings = (ImageSettings)cellValue;
					try {
						HSSFClientAnchor anchor = 
								new HSSFClientAnchor(
									0, 
									0, 
									0, 
									0, 
									(short)(i), 
									rowIndex, 
									(short)(i + 1), 
									rowIndex+1
									);
						anchor.setAnchorType(imageSettings.getAnchorType());
						patriarch.createPicture(anchor, imageSettings.getIndex());
					} catch (Exception ex) {
						throw 
							new JRException(
								EXCEPTION_MESSAGE_KEY_CANNOT_ADD_CELL, 
								null,
								ex);
					} catch (Error err) {
						throw 
							new JRException(
								EXCEPTION_MESSAGE_KEY_CANNOT_ADD_CELL, 
								null,
								err);
					}
				}
			}
			
			if(cellSettings.getCellStyle() != null) {
				cell.setCellStyle(cellSettings.getCellStyle());
			}
			if(cellSettings.getFormula() != null) {
				// the formula text will be stored in formulaCellsMap in order to be applied only after 
				// all defined names are created and available in the workbook (see #closeWorkbook())
				formulaCellsMap.put(cell, cellSettings.getFormula());
			}
			if(cellSettings.getLink() != null) {
				cell.setHyperlink(cellSettings.getLink());
			}
		}
	}
	++rowIndex;
}
 
Example #11
Source File: PictureSheetGenerator.java    From ermasterr with Apache License 2.0 4 votes vote down vote up
private void setImage(final HSSFWorkbook workbook, final HSSFSheet sheet, final CellLocation cellLocation, int width, int height) {
    POIUtils.setCellValue(sheet, cellLocation, "");

    if (imageBuffer != null) {
        final HSSFPatriarch patriarch = sheet.createDrawingPatriarch();

        final HSSFPicture picture = patriarch.createPicture(new HSSFClientAnchor(), pictureIndex);

        final Dimension dimension = picture.getImageDimension();
        final float rate = (float) dimension.width / (float) dimension.height;
        final float specifiedRate = (float) width / (float) height;

        if (width == -1 || height == -1) {
            width = dimension.width;
            height = dimension.height;

        } else {
            if (rate > specifiedRate) {
                if (dimension.width > width) {
                    height = (int) (width / rate);

                } else {
                    width = dimension.width;
                    height = dimension.height;
                }

            } else {
                if (dimension.height > height) {
                    width = (int) (height * rate);

                } else {
                    width = dimension.width;
                    height = dimension.height;
                }
            }
        }

        final HSSFClientAnchor preferredSize = getPreferredSize(sheet, new HSSFClientAnchor(0, 0, 0, 0, (short) cellLocation.c, cellLocation.r, (short) 0, 0), width, height);
        picture.setAnchor(preferredSize);
    }
}
 
Example #12
Source File: ExcelExportOfTemplateUtil.java    From jeewx with Apache License 2.0 4 votes vote down vote up
/**
 * 图片类型的Cell
 * 
 * @param patriarch
 * 
 * @param entity
 * @param row
 * @param i
 * @param string
 * @param obj
 * @param workbook
 * @throws Exception
 */
private static void createImageCell(Drawing patriarch,
		ExcelExportEntity entity, Row row, int i, String field,
		Object obj, Workbook workbook) throws Exception {
	if(StringUtils.isEmpty(field)){return;}
	row.setHeight((short) (50 * entity.getHeight()));
	row.createCell(i);
	ClientAnchor anchor = workbook instanceof HSSFWorkbook?
			new HSSFClientAnchor(0, 0, 0, 0, (short) i,
			row.getRowNum(), (short) (i + 1), row.getRowNum() + 1):
				new XSSFClientAnchor(0, 0, 0, 0, (short) i,
						row.getRowNum(), (short) (i + 1), row.getRowNum() + 1);
	if (entity.getExportImageType() == 1) {
		ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
		BufferedImage bufferImg;
		try {
			String path = ExcelExportOfTemplateUtil.class.getClassLoader()
					.getResource("") + field;
			path = path.replace("WEB-INF/classes/", "");
			path = path.replace("file:/", "");
			bufferImg = ImageIO.read(new File(path));
			ImageIO.write(
					bufferImg,
					field.substring(field.indexOf(".") + 1,
							field.length()), byteArrayOut);
			patriarch.createPicture(
					anchor,
					row.getSheet()
							.getWorkbook()
							.addPicture(byteArrayOut.toByteArray(),
									Workbook.PICTURE_TYPE_JPEG));
		} catch (IOException e) {
			e.printStackTrace();
		}
	} else {
		byte[] value = (byte[]) (entity.getGetMethods() != null ? getFieldBySomeMethod(
				entity.getGetMethods(), obj) : entity.getGetMethod()
				.invoke(obj, new Object[] {}));
		if (value != null) {
			patriarch.createPicture(anchor, row.getSheet().getWorkbook()
					.addPicture(value, Workbook.PICTURE_TYPE_JPEG));
		}
	}

}
 
Example #13
Source File: SpreadsheetSetCellComment.java    From openbd-core with GNU General Public License v3.0 4 votes vote down vote up
public cfData execute( cfSession _session, List<cfData> parameters ) throws cfmRunTimeException {
	if ( parameters.get(2).getDataType() != cfData.CFSTRUCTDATA )
		throwException(_session, "parameter must be of type structure");

	cfSpreadSheetData	spreadsheet = null;
	cfStructData commentS = null;
	int rowNo, columnNo;
	
	/*
	 * Collect up the parameters
	 */
spreadsheet	= (cfSpreadSheetData)parameters.get(3);
commentS		= (cfStructData)parameters.get(2);
rowNo				= parameters.get(1).getInt() - 1;
columnNo		= parameters.get(0).getInt() - 1;
		
if ( rowNo < 0 )
	throwException(_session, "row must be 1 or greater (" + rowNo + ")");
if ( columnNo < 0 )
	throwException(_session, "column must be 1 or greater (" + columnNo + ")");


/*
 * Perform the insertion
 */
Sheet	sheet = spreadsheet.getActiveSheet();
Row row	= sheet.getRow( rowNo );
if ( row == null )
	row	= sheet.createRow( rowNo );

Cell cell	= row.getCell( columnNo );
if ( cell == null )
	cell = row.createCell( columnNo );


// Create the anchor
HSSFClientAnchor clientAnchor = new HSSFClientAnchor();
if ( commentS.containsKey("anchor") ){
	String[] anchor	= commentS.getData("anchor").getString().split(",");
	if ( anchor.length != 4 )
		throwException(_session,"Invalid 'anchor' attribute, should be 4 numbers");
		
		clientAnchor.setRow1( Integer.valueOf( anchor[0] ) - 1 );
		clientAnchor.setCol1( Integer.valueOf( anchor[1] ) - 1 );
		clientAnchor.setRow2( Integer.valueOf( anchor[2] ) - 1 );
		clientAnchor.setCol2( Integer.valueOf( anchor[3] ) - 1 );
}else{
		clientAnchor.setRow1( rowNo );
		clientAnchor.setCol1( columnNo );
		clientAnchor.setRow2( rowNo + 2 );
		clientAnchor.setCol2( columnNo + 2 );
}

// Create the comment
Comment comment = spreadsheet.getActiveSheet().createDrawingPatriarch().createCellComment(clientAnchor);

if ( commentS.containsKey("author") ){
	comment.setAuthor( commentS.getData("author").getString() );
}

if ( commentS.containsKey("visible") ){
	comment.setVisible( commentS.getData("visible").getBoolean() );
}

if ( commentS.containsKey("comment") ){
	HSSFRichTextString richText = new HSSFRichTextString( commentS.getData("comment").getString() );
	try {
		richText.applyFont( SpreadSheetFormatOptions.createCommentFont(spreadsheet.getWorkBook(), commentS) );
	} catch (Exception e) {
		throwException( _session, e.getMessage() );
	}
	
	comment.setString( richText );
}

cell.setCellComment( comment );
	return cfBooleanData.TRUE;
}
 
Example #14
Source File: PictureSheetGenerator.java    From ermaster-b with Apache License 2.0 4 votes vote down vote up
private void setImage(HSSFWorkbook workbook, HSSFSheet sheet,
			CellLocation cellLocation, int width, int height) {
		POIUtils.setCellValue(sheet, cellLocation, "");
System.out.println("this.imageBuffer:" + this.imageBuffer);
		if (this.imageBuffer != null) {
			HSSFPatriarch patriarch = sheet.createDrawingPatriarch();

			HSSFPicture picture = patriarch.createPicture(
					new HSSFClientAnchor(), this.pictureIndex);

			Dimension dimension = picture.getImageDimension();
			float rate = dimension.width / dimension.height;
			float specifiedRate = width / height;

			if (width == -1 || height == -1) {
				width = dimension.width;
				height = dimension.height;
				
			} else {
				if (rate > specifiedRate) {
					if (dimension.width > width) {
						height = (int) (width / rate);

					} else {
						width = dimension.width;
						height = dimension.height;
					}

				} else {
					if (dimension.height > height) {
						width = (int) (height * rate);

					} else {
						width = dimension.width;
						height = dimension.height;
					}
				}
			}

			HSSFClientAnchor preferredSize = this.getPreferredSize(sheet,
					new HSSFClientAnchor(0, 0, 0, 0, (short) cellLocation.c,
							cellLocation.r, (short) 0, 0), width, height);
			picture.setAnchor(preferredSize);
		}
	}