我有一个excel中含有多张照片,我想要按照将里面的图片全部适应单元格大小并居中处理 ,有什么好的方法吗? 最好性能上是比较好
请参阅以下示例代码来完成您的任务。请参考它,然后根据您的需要编写/更新您的代码。
例如,
示例代码:
//Open the Excel file
Workbook workbook = new Workbook("d:\\files\\Book1.xlsx");
Worksheet worksheet = workbook.getWorksheets().get(0);
//Get all the images in the worksheet
PictureCollection pictures = worksheet.getPictures();
for (int i = 0; i < pictures.getCount(); i++)
{
Picture picture = pictures.get(i);
//Get the cell containing the picture
int row = picture.getUpperLeftRow();
int column = picture.getUpperLeftColumn();
Cell cell = worksheet.getCells().get(row, column);
double cellWidth = worksheet.getCells().getColumnWidthPixel(column);
double cellHeight = worksheet.getCells().getRowHeightPixel(row);
//Get the original dimensions of the picture
double picWidth = picture.getWidth();
double picHeight = picture.getHeight();
//Calculate the scale factors to fit the image within the cell
double scaleX = cellWidth / picWidth;
double scaleY = cellHeight / picHeight;
//Choose the smaller scale to maintain the aspect ratio
double scale = Math.min(scaleX, scaleY);
//Resize the picture
picture.setWidth((int)(picWidth * scale));
picture.setHeight((int)(picHeight * scale));
//Center the image within the cell by adjusting the left and top offsets
int leftOffset = (int)((cellWidth - picture.getWidth()) / 2);
int topOffset = (int)((cellHeight - picture.getHeight()) / 2);
picture.setLeft(leftOffset);
picture.setTop(topOffset);
}
//Save the updated workbook
workbook.save("d:\\files\\out1.xlsx");
希望这会有所帮助。
@xiaoman
你可以使用单元格嵌入图片来实现需求,请查看附件。result.zip (4.1 MB)
样例代码如下:
//Open the Excel file
Workbook workbook = new Workbook(filePath + "sample.xlsx");
Worksheet worksheet = workbook.getWorksheets().get(0);
//Get all the images in the worksheet
PictureCollection pictures = worksheet.getPictures();
for (int i = 0; i < pictures.getCount(); i++)
{
Picture picture = pictures.get(i);
//Get the cell containing the picture
int row = picture.getUpperLeftRow();
int column = picture.getUpperLeftColumn();
Cell cell = worksheet.getCells().get(row, column);
Style style = cell.getStyle();
style.setHorizontalAlignment(TextAlignmentType.CENTER);
style.setVerticalAlignment(TextAlignmentType.CENTER);
cell.setEmbeddedImage(picture.getData());
cell.setStyle(style);
}
pictures.clear();
//Save the updated workbook
workbook.save(filePath + "out_java.xlsx");
@xiaoman ,
放在单元格中的图片(Placed in Cell Picture)是Microsoft Excel的新的特性,如果你使用的是WPS或者低版本的Microsoft Excel,此特性可能没有支持。
你可以尝试 @amjad.sahi 的解决方案: