Читать встроенный объект в Excel, используя Java - PullRequest
1 голос
/ 19 марта 2012

Я хочу сделать один лист Excel, который мне нужно отправить другому для заполнения. В листе Excel другой человек заполняет свою информацию и также может прикрепить текстовый / документальный файл с листом Excel ... Мне нужно получить доступ к этому тексту / документу. Пожалуйста, предоставьте мне решение. Я использую Apache POI - HSSF api.

Заранее спасибо.

</p> <pre>package excelExchange; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Iterator; import java.util.Vector; import org.apache.poi.hslf.HSLFSlideShow; import org.apache.poi.hslf.usermodel.SlideShow; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFObjectData; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hwpf.HWPFDocument; import org.apache.poi.poifs.filesystem.DirectoryNode; //import org.apache.poi.h; import org.apache.poi.poifs.filesystem.*; public class ReadEmbeddedObject { public static void main(String[] args) throws IOException { String fileName = "C:\\Mayur\\NewsLetter\\files\\projectInfo.xls"; //Vector dataHolder = ReadCSV(fileName); } public static void ReadCSV(String fileName) throws IOException{ Vector cellVectorHolder = new Vector(); FileInputStream myInput = new FileInputStream(fileName); // myFileSystem=fs //myWorkBook=workbook POIFSFileSystem fs = new POIFSFileSystem(myInput); HSSFWorkbook workbook = new HSSFWorkbook(fs); for (HSSFObjectData obj : workbook.getAllEmbeddedObjects()) { //the OLE2 Class Name of the object System.out.println("Objects : "+ obj.getOLE2ClassName()+ " 2 ."); String oleName = obj.getOLE2ClassName(); if (oleName.equals("Worksheet")) { System.out.println("Worksheet"); DirectoryNode dn = (DirectoryNode) obj.getDirectory(); HSSFWorkbook embeddedWorkbook = new HSSFWorkbook(dn, fs, false); System.out.println(oleName+": " + embeddedWorkbook.getNumberOfSheets()); System.out.println("Information :--- "); System.out.println(" name " + embeddedWorkbook.getSheetName(0)); //System.out.println(entry.getName() + ": " + embeddedWorkbook.getNumberOfSheets()); } else if (oleName.equals("Document")) { System.out.println("Document"); DirectoryNode dn = (DirectoryNode) obj.getDirectory(); HWPFDocument embeddedWordDocument = new HWPFDocument(dn,fs); System.out.println("Doc : " + embeddedWordDocument.getRange().text()); } else if (oleName.equals("Presentation")) { System.out.println("Presentation"); DirectoryNode dn = (DirectoryNode) obj.getDirectory(); SlideShow embeddedPowerPointDocument = new SlideShow(new HSLFSlideShow(dn, fs)); //Entry entry = (Entry) entries.next(); System.out.println(": " + embeddedPowerPointDocument.getSlides().length); } else { System.out.println("Else part "); if(obj.hasDirectoryEntry()){ // The DirectoryEntry is a DocumentNode. Examine its entries to find out what it is DirectoryNode dn = (DirectoryNode) obj.getDirectory(); for (Iterator entries = dn.getEntries(); entries.hasNext();) { Entry entry = (Entry) entries.next(); System.out.println(oleName + "." + entry.getName()); } } else { // There is no DirectoryEntry // Recover the object's data from the HSSFObjectData instance. byte[] objectData = obj.getObjectData(); } } } } }

Ответы [ 2 ]

1 голос
/ 19 марта 2012

POI имеет API для перебора встроенных объектов. (HSSFWorkbook .getAllEmbeddedObjects или XSSFWorkbook.getAllEmbedds). Примеры тут http://poi.apache.org/spreadsheet/quick-guide.html#Embedded

0 голосов
/ 09 мая 2017
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;

/**
 * Demonstrates how you can extract embedded data from a .xlsx file
 */
public class GetEmbedded {

    public static void main(String[] args) throws Exception {
        String path = "SomeExcelFile.xlsx"
        XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(new File(path)));

             for (PackagePart pPart : workbook.getAllEmbedds()) {
                            String contentType = pPart.getContentType();
                            if (contentType.equals("application/vnd.ms-excel")) { //This is to read xls workbook embedded to xlsx file
                                HSSFWorkbook embeddedWorkbook = new HSSFWorkbook(pPart.getInputStream());
                                int countOfSheetXls=embeddedWorkbook.getNumberOfSheets();

                 }
                            else if (contentType.equals("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")) { //This is to read xlsx workbook embedded to xlsx file
                                 if(pPart.getPartName().getName().equals("/xl/embeddings/Microsoft_Excel_Worksheet12.xlsx")){
                                 //"/xl/embeddings/Microsoft_Excel_Worksheet12.xlsx" - Can read an Excel from a particular sheet 
                                // This is the worksheet from the Parent Excel-sheet-12

                                     XSSFWorkbook embeddedWorkbook = new XSSFWorkbook(pPart.getInputStream());
                                     int countOfSheetXlsx=embeddedWorkbook.getNumberOfSheets();
                                     ArrayList<String> sheetNames= new ArrayList<String>();
                                        for(int i=0;i<countOfSheetXlsx;i++){
                                        String name=workbook.getSheetName(i);
                                        sheetNames.add(name);
                                        }
                                }
                            }
                }
     }
}
...