获取Excel文件中的图像大小(高度和宽度),而不是使用Apache POI时的原始大小(对于xls和xlsx文件),可以通过以下步骤实现:
以下是一个示例代码片段,演示如何获取Excel文件中图像的大小:
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFPictureData;
import org.apache.poi.xssf.usermodel.XSSFPictureData;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class ExcelImageSizeExtractor {
public static void main(String[] args) {
String filePath = "path/to/excel/file.xlsx";
List<ImageSize> imageSizes = getImageSizes(filePath);
for (ImageSize imageSize : imageSizes) {
System.out.println("Image Size - Width: " + imageSize.getWidth() + ", Height: " + imageSize.getHeight());
}
}
public static List<ImageSize> getImageSizes(String filePath) {
List<ImageSize> imageSizes = new ArrayList<>();
try (Workbook workbook = getWorkbook(filePath)) {
for (Sheet sheet : workbook) {
Drawing<?> drawing = sheet.getDrawingPatriarch();
if (drawing != null) {
for (Shape shape : drawing) {
if (shape instanceof Picture) {
Picture picture = (Picture) shape;
ClientAnchor anchor = picture.getClientAnchor();
int row1 = anchor.getRow1();
int row2 = anchor.getRow2();
int col1 = anchor.getCol1();
int col2 = anchor.getCol2();
int height = (row2 - row1 + 1) * sheet.getDefaultRowHeight();
int width = (col2 - col1 + 1) * sheet.getColumnWidth(col1);
imageSizes.add(new ImageSize(width, height));
}
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
return imageSizes;
}
private static Workbook getWorkbook(String filePath) throws IOException {
FileInputStream fileInputStream = new FileInputStream(filePath);
if (filePath.endsWith(".xls")) {
return new HSSFWorkbook(fileInputStream);
} else if (filePath.endsWith(".xlsx")) {
return new XSSFWorkbook(fileInputStream);
}
throw new IllegalArgumentException("Unsupported file format");
}
private static class ImageSize {
private int width;
private int height;
public ImageSize(int width, int height) {
this.width = width;
this.height = height;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
}
}
请注意,上述示例代码仅适用于获取Excel文件中的图像大小,而不是使用Apache POI时的原始大小。对于其他问题或需求,可能需要使用不同的方法或库来解决。
领取专属 10元无门槛券
手把手带您无忧上云