本文将介绍如何使用Spire.XLS for Java提取Excel中的OLE对象。
import com.spire.xls.*;
import com.spire.xls.core.IOleObject;
import java.io.*;
public class ExtractOLEObjects {
public static void main(String[] args){
//创建Workbook实例
Workbook workbook = new Workbook();
//加载Excel文档
workbook.loadFromFile("OLEObjectsExample.xlsx");
//获取第一张工作表
Worksheet sheet = workbook.getWorksheets().get(0);
//提取工作表中的OLE对象
if (sheet.hasOleObjects()) {
for (int i = 0; i < sheet.getOleObjects().size(); i++) {
IOleObject object = sheet.getOleObjects().get(i);
OleObjectType type = sheet.getOleObjects().get(i).getObjectType();
switch (type) {
//Word文档
case WordDocument:
byteArrayToFile(object.getOleData(), "output/extractOLE.docx");
break;
//PowerPoint文档
case PowerPointSlide:
byteArrayToFile(object.getOleData(), "output/extractOLE.pptx");
break;
//PDF文档
case AdobeAcrobatDocument:
byteArrayToFile(object.getOleData(), "output/extractOLE.pdf");
break;
//Excel文档
case ExcelWorksheet:
byteArrayToFile(object.getOleData(), "output/extractOLE.xlsx");
break;
}
}
}
}
public static void byteArrayToFile(byte[] datas, String destPath) {
File dest = new File(destPath);
try (InputStream is = new ByteArrayInputStream(datas);
OutputStream os = new BufferedOutputStream(new FileOutputStream(dest, false));) {
byte[] flush = new byte[1024];
int len = -1;
while ((len = is.read(flush)) != -1) {
os.write(flush, 0, len);
}
os.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
提取结果: