使用apache poi Java读取嵌入的excel

问题描述 投票:0回答:1

有没有一种方法可以读取Java中嵌入的excel文件,如下图所示

目前我正在使用下面的代码来读取excel文件

File xlsxFile = new File("test.xlsx");
        
inputStream = new FileInputStream(xlsxFile);

XSSFWorkbook workbook = new XSSFWorkbook(inputStream);

XSSFSheet sheet = workbook.getSheetAt(4);
java excel apache-poi xssfworkbook xssfsheet
1个回答
0
投票

您的嵌入对象在第五张图纸的图纸形状中可见。

要获取对象数据,您可以迭代该绘图的所有形状。如果形状是

XSSFObjectData
的实例,那么它是对象数据形状。如果内容类型为“application/vnd.openxmlformats-officedocument.spreadsheetml.sheet”,则 object-data-shape 链接到包含 Office Open XML 格式的 Excel 电子表格数据的包部件 (
XSSF
)。如果是这样,那么您可以从该包部分的输入流中获取
XSSFWorkbook

示例代码:

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();
 }
}
© www.soinside.com 2019 - 2024. All rights reserved.