[英]Is there any way to read both .xls and .xlsx files using Apache POI?
[英]Get the image size (height and width) in excel files instead of the original size when using Apache POI (for both xls and xlsx files)
目前我們正在開發一個 api 來將 xls 和 xlsx 文件轉換為 html,我們希望保留圖像(excel 文件中的大小和位置)我們希望獲得與我們在 excel 文件中看到的完全相同的圖像大小(調整大小后)。 我們嘗試了這種方法:
for (HSSFPictureData pic : workbook.getAllPictures()) {
InputStream in = new ByteArrayInputStream(pic.getData());
BufferedImage image = ImageIO.read(in);
System.out.println(image.getWidth() + ":" + image.getHeight());
}
但它返回了原始大小,而不是我們在 excel 文件中調整大小的大小。 有沒有辦法實現這一目標?
Workbook.getAllPictures()
獲取嵌入在Excel
文件中的所有圖片文件。 這些圖片文件包含純圖片數據。 所以沒有任何方法可以獲得縮放后的圖片大小。
縮放的圖片包含在圖紙中並錨定到圖紙的單元格中。 因此,要獲得縮放的圖片,需要遍歷圖紙以從中獲取Picture
。 從Picture
一可以得到工作表中的錨定位置、錨點的尺寸(又名縮放尺寸)以及PictureData
。
完整示例(使用當前的apache poi 5.0.0
測試和工作,適用於HSSF
和XSSF
)。
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFDrawing;
import org.apache.poi.hssf.usermodel.HSSFPatriarch;
import org.apache.poi.ss.util.ImageUtils;
import org.apache.poi.util.Units;
import java.awt.Dimension;
import java.io.FileInputStream;
import java.util.List;
class ExcelGetPicturesWithPositionAndSize {
public static void main(String[] args) throws Exception {
//Workbook workbook = WorkbookFactory.create(new FileInputStream("ExcelWithImages.xlsx"));
Workbook workbook = WorkbookFactory.create(new FileInputStream("ExcelWithImages.xls"));
for (Sheet sheet : workbook) {
String sheetname = sheet.getSheetName();
Drawing drawing = sheet.getDrawingPatriarch();
List<?> shapes = null;
if (drawing instanceof XSSFDrawing) {
shapes = ((XSSFDrawing)drawing).getShapes();
} else if (drawing instanceof HSSFPatriarch) {
shapes = ((HSSFPatriarch)drawing).getChildren();
}
for (Object shape : shapes) {
if (shape instanceof Picture) {
Picture picture = (Picture)shape;
String shapename = picture.getShapeName();
int row = picture.getClientAnchor().getRow1();
int col = picture.getClientAnchor().getCol1();
System.out.println(
"Picture with Shapename: " + shapename +
" is located sheet: " + sheetname +
", row: " + row +
", col: " + col
);
Dimension dimension = ImageUtils.getDimensionFromAnchor(picture);
System.out.println(
"Picture's size in EMU: width=" + dimension.getWidth() + ", height=" + dimension.getHeight() +
", in pixel: width=" + dimension.getWidth()/Units.EMU_PER_PIXEL + ", height=" + dimension.getHeight()/Units.EMU_PER_PIXEL
);
PictureData pictureData = picture.getPictureData();
System.out.println(
"Picture's data: bytes=" + pictureData.getData().length +
", mime type=" + pictureData.getMimeType() +
", suggested file extension=" + pictureData.suggestFileExtension()
);
}
}
}
workbook.close();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.