Is there a way to read embedded excel file in Java as shown in the below image
Currently I'm using the below piece of code to read the excel file
File xlsxFile = new File("test.xlsx");
inputStream = new FileInputStream(xlsxFile);
XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
XSSFSheet sheet = workbook.getSheetAt(4);
Your embedded Object is visible in a shape in the sheet drawing of your 5th sheet.
To get the object data, you can iterate over all the shapes of that drawing. If the shape is an instance of XSSFObjectData
, then it is a object-data-shape. If the content type is "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", then the object-data-shape links to a package part which contains Excel spreadsheet data in Office Open XML format (XSSF
). If so, then you can get a XSSFWorkbook
from that package part's input stream.
Example code:
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import java.io.FileInputStream;
class ExcelGetEmbeddedFromShape {
public static void main(String[] args) throws Exception {
String filename = "./ExcelWithEmbedded.xlsx";
Workbook workbook = WorkbookFactory.create(new FileInputStream(filename));
Sheet sheet = workbook.getSheetAt(4);
Drawing drawing = sheet.getDrawingPatriarch();
if (drawing instanceof XSSFDrawing) {
for (XSSFShape shape : ((XSSFDrawing)drawing).getShapes()) {
if (shape instanceof XSSFObjectData) {
XSSFObjectData objectData = (XSSFObjectData)shape;
if ("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet".equals(objectData.getContentType())) {
XSSFWorkbook embeddedWorkbook = (XSSFWorkbook)WorkbookFactory.create(objectData.getObjectPart().getInputStream());
System.out.println(embeddedWorkbook);
//... do something with embeddedWorkbook ...
}
}
}
}
workbook.close();
}
}