Java to generate XML from excel - java

I have a spreadsheet based on which I have to generate a xml file. the file should respect a particular XSD structure and I have to do from Java.
The XML mapping is not working in excel because of "list of lists " issue.
what would be an ideal approach in java to create , domparser or jaxb ?
Any reference is helpful
Here is my code
package exceltoXML;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Writer;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.TreeMap;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.eclipse.jgit.*;
import org.eclipse.jgit.api.CommitCommand;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.PushCommand;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
public class readExcel_class1 {
public static Properties properties;
public static Enumeration<?> en;
public static String SourcePath;
public static String targetPath;
public static Map<String, String> propertiesCaseInsensitiveMap;
public static List<foldermap> foldermaps;
public static void main(String[] args) throws IOException, ParserConfigurationException, TransformerException {
// TODO Auto-generated method stub
Writer writer = null;
try {
foldermaps = new ArrayList<foldermap>();
properties=loadProperties(args[0]);
en=properties.propertyNames();
propertiesCaseInsensitiveMap=new TreeMap<String,String>(String.CASE_INSENSITIVE_ORDER);
while(en.hasMoreElements()){
String key=(String)en.nextElement();
propertiesCaseInsensitiveMap.put(key, properties.getProperty(key));
}
SourcePath=propertiesCaseInsensitiveMap.get("sourcepath");
targetPath=propertiesCaseInsensitiveMap.get("targetPath");
System.out.println("Source Path is "+ SourcePath + " and Target path is " + targetPath);
String fileName = "export_"+new Date().getTime() + ".json";
System.out.println("Output filename is " + fileName);
//System.out.println("Hi");
File myFile = new File("C:\\Users\\abcdra\\Desktop\\cicd\\git_push.xlsm");
FileInputStream fis = new FileInputStream(myFile);
String sourceFileName = SourcePath+fileName;
String targetFileName = targetPath+fileName;
System.out.println("Source FileName : " + sourceFileName);
System.out.println("Target FileName : " + targetFileName);
File file = new File(sourceFileName);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder1 = factory.newDocumentBuilder();
Document document = builder1.newDocument();
Element rootElement = document.createElement("importParams");
document.appendChild(rootElement);
rootElement.setAttribute("xmlns", "http://www.abc.io/oie/importControl/9" );
writer = new BufferedWriter(new FileWriter(file));
// Finds the workbook instance for XLSX file
XSSFWorkbook myWorkBook = new XSSFWorkbook (fis);
// Return first sheet from the XLSX workbook
XSSFSheet mySheet = myWorkBook.getSheetAt(1);
Iterator<Row> rowIterator = mySheet.iterator();
ArrayList<ArrayList<String>> data = new ArrayList<ArrayList<String>>();
foldermap foldermap = new foldermap();
while (rowIterator.hasNext()) {
//System.out.println("Current Row Number : " + rowIterator.next().getRowNum());
Row row = rowIterator.next();
if(row.getRowNum()==0 ){
continue; //just skip the rows if row number is 0
}
// For each row, iterate through each columns
Iterator<Cell> cellIterator = row.cellIterator();
ArrayList<String> rowData = new ArrayList<String>();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
switch (cell.getCellType()) {
case STRING:
//System.out.println ("String: " + cell.getRichStringCellValue ());
rowData.add(cell.getRichStringCellValue() + "");
//System.out.println("Inside cells");
if (cell.getColumnIndex() ==0 )
{
foldermap.setSourceProject(cell.getStringCellValue());
System.out.println("source project " + foldermap.getSourceProject());
}
if (cell.getColumnIndex() ==1 )
{
foldermap.setSourceFolderPath (cell.getStringCellValue());
}
if (cell.getColumnIndex() ==2 )
{
foldermap.setTargetProject(cell.getStringCellValue());
}
if (cell.getColumnIndex() ==3 )
{
foldermap.setTargetFolderPath( cell.getStringCellValue());
}
if (cell.getColumnIndex() ==4 )
{
foldermap.setRecursive(cell.getStringCellValue());
System.out.println("Recursive value " + foldermap.getRecursive());
}
if (cell.getColumnIndex() ==5 )
{
foldermap.setRecursive(cell.getStringCellValue());
System.out.println("Recursive value " + foldermap.getRecursive());
}
break;
case NUMERIC:
System.out.println ("String: " + cell.getNumericCellValue ());
break;
case BOOLEAN:
System.out.print(cell.getBooleanCellValue() + "\t");
break;
default :
}
}
// System.out.println("\n");
writer.write("\n ");
foldermaps.add(foldermap);
}
System.out.println("Writing to text file is completed...");
if (writer != null) {
writer.close();
}
TransformerFactory transformerFactory=TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(document);
//create target path if it does not exist
Element foldermaps1 = document.createElement("folderMaps");
rootElement.appendChild(foldermaps1);
System.out.println("Number of foldermap are " + foldermaps.size());
for (foldermap fm : foldermaps)
{
System.out.println("Source Project is " + fm.getSourceProject());
Element fmap = document.createElement("folderMap");
foldermaps1.appendChild(fmap);
fmap.setAttribute("sourceProject", fm.getSourceProject());
fmap.setAttribute("sourceFolderPath", fm.getSourceFolderPath());
fmap.setAttribute("targetProject", fm.getTargetProject());
fmap.setAttribute("targetFolderPath", fm.getTargetFolderPath());
fmap.setAttribute("recursive", fm.getRecursive());
}
StreamResult result = new StreamResult(new File("C:\\Users\\abcdra\\Desktop\\eclipse_workspace_64\\abc.xml"));
transformer.setOutputProperty
(OutputKeys.INDENT, "yes");
transformer.transform(source, result);
System.out.println("Parameter file successfully created");
}
catch(IOException ex )
{
ex.printStackTrace();
}
}
public static Properties loadProperties(String filename){
Properties props = new Properties();
InputStream input = null;
try {
input = new FileInputStream(filename);
props.load(input);
System.out.println("Loaded properties from: " + filename);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return props;
}
public static void fileCopy (File sourceDirectory , File targetDirectory)
{
try {
Files.copy(sourceDirectory.toPath(),targetDirectory.toPath());
}
catch(Exception e)
{
System.out.println("Error" + e);
}
}
}
The input is like
I am getting the output like
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<importParams xmlns="http://www.informatica.com/oie/importControl/9">
<folderMaps>
<folderMap recursive="truth" sourceFolderPath="Hive" sourceProject="Unknown1" targetFolderPath="import" targetProject="Unknown"/>
<folderMap recursive="truth" sourceFolderPath="Hive" sourceProject="Unknown1" targetFolderPath="import" targetProject="Unknown"/>
</folderMaps>
</importParams>
Both elements have value unknown1 , so the last element is repeating ,any idea how to avoid that. the output I am expecting is
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<importParams xmlns="http://www.informatica.com/oie/importControl/9">
<folderMaps>
<folderMap recursive="truth" sourceFolderPath="Hive" sourceProject="Unknown" targetFolderPath="import" targetProject="Unknown"/>
<folderMap recursive="truth" sourceFolderPath="Hive" sourceProject="Unknown1" targetFolderPath="import" targetProject="Unknown"/>
</folderMaps>
</importParams>

There is quite a bit of code here, but I think the issue is that the foldermap is not being created new each time inside the row loop.
foldermap foldermap = new foldermap();
while (rowIterator.hasNext()) {
...
foldermaps.add(foldermap);
}
So the foldermap is being updated, but added multiple times.
Move the new foldermap(); inside the while loop so that on each row, there is a new entry.
I think, if I read the code correctly, you can do:
while (rowIterator.hasNext()) {
foldermap foldermap = new foldermap();
...
As the foldermap does not need scope outside of the while loop for the rowIterator.

Related

org.xml.sax.SAXParseException error while integrating XML for generating PDF

While Running the following code in order to read an XML file and generating a corresponding PDF. I am facing the errors mentioned below the code.
package com.test.pdf;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import com.google.zxing.WriterException;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfDocument;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.parser.PdfTextExtractor;
import com.itextpdf.xmp.impl.Base64;
//import com.itextpdf.text.pdf.codec.Base64;
import org.apache.log4j.Logger;
public class PDFGenerator {
final static Logger logger = Logger.getLogger(PDFGenerator.class);
private static final String TITLE = "TestReport";
public static final String PDF_EXTENSION = ".pdf";
public static String arg1 = "";
public static String arg2 = "";
public static String arg3 = "";
public static String createPDFBase64(String arg1 , String arg2 , String arg3) throws IOException, URISyntaxException, com.lowagie.text.DocumentException, WriterException {
byte[] encoded = null;
String out= null;
Document document = new Document();
try {
//arg1 = args[0];
//Document is not auto-closable hence need to close it separately
document = new Document(PageSize.LETTER);
System.out.println("Here i amn777");
File temp = File.createTempFile(TITLE ,PDF_EXTENSION);
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(
temp)); // new File
HeaderFooter event = new HeaderFooter(arg2);
event.setHeader("Test Report");
writer.setPageEvent(event);
document.open();
PDFCreator pdfCreator = new PDFCreator();
pdfCreator.addMetaData(document, arg1 , arg2 );
pdfCreator.addTitlePage(document, arg2 );
//PDFCreator.addContent(document, dataObjList);
//String base64String = Base64.encodeFromFile("C:\\Users\\2000554\\Downloads\\HTMLToPDF\\TestReport.pdf");
//System.out.println("===============>>>" + base64String);
document.close();
byte[] inFileBytes = Files.readAllBytes(temp.toPath());
//PdfReader pReader = new PdfReader(inFileBytes);
//System.out.println("pReader.getFileLength()===============>>>" + pReader.getFileLength());
//System.out.println("pReader.getFileLength()===============>>>" + PdfTextExtractor.getTextFromPage(pReader, 1));
out = new String(Base64.encode(inFileBytes), "UTF-8");
System.out.println("Clear cache..");
pdfCreator.xmlData.clear();
pdfCreator.dataObjMRCList.clear();
pdfCreator.dataObjNRCList.clear();
pdfCreator.dataObjVASList.clear();
pdfCreator.dataObjDEVList.clear();
pdfCreator.stcPhoneNumDispList.clear();
pdfCreator.stcSvcMap.clear();
pdfCreator.stcSvcBandWthMap.clear();
pdfCreator.invoiceTaxDvcMap.clear();
//byte[] decoded = java.util.Base64.getDecoder().decode(out.getBytes());
/* byte[] decoded = Base64.decode(out.getBytes());
FileOutputStream fos = new FileOutputStream("C:\\Users\\2000554\\Downloads\\HTMLToPDF\\TestBaseReport.pdf");
fos.write(decoded);
fos.flush();
fos.close();*/
}catch ( FileNotFoundException e) {
System.out.println("FileNotFoundException occurs.." + e.getMessage());
e.printStackTrace();
}catch (DocumentException e) {
System.out.println("DocumentException occurs.." + e.getMessage());
e.printStackTrace();
} catch (Exception e) {
System.out.println("Exception occurs.." + e.getMessage());
e.printStackTrace();
return null;
}
finally{
if(null != document){
// document.close();
}
}
return out;
}
public static void main(String args[]) {
try {
if(args != null && args.length>1) {
FileReader fReader = new FileReader(new File("C:\\Users\\2004807\\Downloads\\XML\\Amendment.xml"));
BufferedReader bdr = new BufferedReader(fReader);
String line = null;
String xmlString = "";
while ((line=bdr.readLine())!=null){
xmlString += line;
}
createPDFBase64(xmlString,args[1],args[2]);
}else {
createPDFBase64("","","");
}
} catch (IOException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (com.lowagie.text.DocumentException e) {
e.printStackTrace();
} catch (WriterException e) {
e.printStackTrace();
}
}
}
I rechecked the path and the XML format since the error mentioned is due to wrong formatting of XML in some cases. I still am getting the following error.
Here i amn777
1getting resourcesfile:/C:/Users/2004807/Desktop/B2B%20Java/HtmlToPdf/target/classes/new.PNG
Inside getXMLData
XML==>
[Fatal Error] :1:1: Premature end of file.
Error is :org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 1; Premature end of file.
xmlData size is :0

Can i take a screenshot and paste it in a word file in appium using Java?

I'm currently using the below method to take screenshots and store them in a folder called 'Screenshots'. But what i want is, to take these screenshots and paste them in a word document according to the test cases to which they belong.
Is it possible? If so could somebody please guide me?
public String FailureScreenshotAndroid(String name) {
try {
Date d = new Date();
String date = d.toString().replace(":", "_").replace(" ", "_");
TakesScreenshot t = (TakesScreenshot)driver;
File f1 = t.getScreenshotAs(OutputType.FILE);//Temporary Location
String permanentLocation =System.getProperty("user.dir")+ "\\Screenshots\\"+name+date+".png";
File f2 = new File(permanentLocation);
FileUtils.copyFile(f1, f2);
return permanentLocation;
}catch (Exception e) {
String msg = e.getMessage();
return msg;
}
}
Try below:
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;
import javax.imageio.ImageIO;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFRun;
public class TakeScreenshots {
public static void main(String[] args) {
try {
XWPFDocument docx = new XWPFDocument();
XWPFRun run = docx.createParagraph().createRun();
FileOutputStream out = new FileOutputStream("d:/xyz/doc1.docx");
for (int counter = 1; counter <= 5; counter++) {
captureScreenShot(docx, run, out);
TimeUnit.SECONDS.sleep(1);
}
docx.write(out);
out.flush();
out.close();
docx.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void captureScreenShot(XWPFDocument docx, XWPFRun run, FileOutputStream out) throws Exception {
String screenshot_name = System.currentTimeMillis() + ".png";
BufferedImage image = new Robot()
.createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
File file = new File("d:/xyz/" + screenshot_name);
ImageIO.write(image, "png", file);
InputStream pic = new FileInputStream("d:/xyz/" + screenshot_name);
run.addBreak();
run.addPicture(pic, XWPFDocument.PICTURE_TYPE_PNG, screenshot_name, Units.toEMU(350), Units.toEMU(350));
pic.close();
file.delete();
}
}

insert data stored in array list in excel using java

Its been a while i m trying to create a excel sheet to store the crawled data in a table format in a excel , the data is fetched from a url and stored in a array list , this data is needed to be stored in a array list `
import java.util.ArrayList;
import com.webscrap4j.WebScrap;
import com.webscrap4j.WebScrapException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
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.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFTable;
public class crawl
{
public static void main(String[] args) throws IOException {
ArrayList<String> al = new ArrayList<String>();
ArrayList<String> bl = new ArrayList<String>();
ArrayList<String> cl = new ArrayList<String>();
WebScrap ws = new WebScrap();
ws.setUrl("https://www.pepperfry.com/hardware-electricals-power-storage-ups-inverters.html");
try
{
ws.startWebScrap();
//al = ws.getImageTagData("img", "title");
al = ws.getSingleHTMLScriptData("<div class='card-body-title hidden-txt'>", "</div>");
bl = ws.getSingleHTMLScriptData("<span class='strike'>", "</span>");
cl = ws.getSingleHTMLScriptData("<p class='card-body-price txt-red'>", "</p>");
/* FileOutputStream fos=new FileOutputStream("/Users/parthpatil/Documents/11.xls");
HSSFWorkbook workBook = new HSSFWorkbook();
HSSFSheet Sheet = workBook.createSheet("products");
//XSSFTable my_table = Sheet.createTable();
HSSFRow row;
HSSFCell cell;
CreationHelper helper = workBook.getCreationHelper();
Row header = Sheet.createRow(0);
header.createCell(0).setCellValue("Product Name");
header.createCell(1).setCellValue("Product Price");
header.createCell(2).setCellValue("Product MRP");
for(int i=0;i<al.size();i++){
row = Sheet.createRow((short) i);
cell = row.createCell(i);
System.out.println(al.get(i));
cell.setCellValue(al.get(i).toString());
}
System.out.println("Done");
workBook.write(fos);
*/
for (String adata : al)
{
System.out.println("the product are:- " + adata);
}
for (String bdata : bl)
{
System.out.println("the MRp are:- " + bdata);
}
for (String cdata : cl)
{
System.out.println("the selling price is:- " + cdata);
}
} catch (WebScrapException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Your code is globally correct it has only some little mistakes, here is how it could be done with your code:
// Use the try-with-resource statement to close all the resources properly
try (HSSFWorkbook workBook = new HSSFWorkbook();
FileOutputStream fos = new FileOutputStream("/Users/parthpatil/Documents/11.xls")) {
// Create the Sheet
HSSFSheet Sheet = workBook.createSheet("products");
// Create the first row corresponding to the header
Row header = Sheet.createRow(0);
header.createCell(0).setCellValue("Product Name");
header.createCell(1).setCellValue("Product Price");
header.createCell(2).setCellValue("Product MRP");
// Ensure that all the List have the same size otherwise throw an exception
if (al.size() != bl.size() || al.size() != cl.size())
throw new IllegalStateException("Some data is missing");
// Iterate over all the list an create the rows of data
for(int i = 0; i < al.size(); i++){
// Create the current starting from 1 to al.size()
HSSFRow row = Sheet.createRow((short) i + 1);
// Cell of the Product Name
row.createCell(0).setCellValue(al.get(i));
// Cell of the Product Price
row.createCell(1).setCellValue(cl.get(i));
// Cell of the Product MRP
row.createCell(2).setCellValue(bl.get(i));
}
// Write the result into the file
workBook.write(fos);
}

Invalid outout when writing to file with java

I'm trying to write the output to a csv file but the first values are in this format
I used ObjectOutputStream. Normally the first values should be 1,1,1,2,2,2,3....
Here is my code any ideas please ?
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.List;
import org.apache.mahout.cf.taste.common.TasteException;
import org.apache.mahout.cf.taste.impl.common.LongPrimitiveIterator;
import org.apache.mahout.cf.taste.impl.model.file.FileDataModel;
import org.apache.mahout.cf.taste.impl.recommender.GenericItemBasedRecommender;
import org.apache.mahout.cf.taste.impl.similarity.LogLikelihoodSimilarity;
import org.apache.mahout.cf.taste.model.DataModel;
import org.apache.mahout.cf.taste.recommender.RecommendedItem;
import org.apache.mahout.cf.taste.similarity.ItemSimilarity;
public class ItemRecommend {
public static void main(String[] args) throws IOException {
FileOutputStream fos = new FileOutputStream("data/test.csv");
ObjectOutputStream oos = new ObjectOutputStream(fos);
try {
DataModel dm = new FileDataModel(new File("data/rated.csv"));
ItemSimilarity sim = new LogLikelihoodSimilarity(dm);
GenericItemBasedRecommender recommender = new GenericItemBasedRecommender(dm, sim);
for (LongPrimitiveIterator items = dm.getItemIDs(); items.hasNext();){
long itemID = (int)(long) items.nextLong();
List<RecommendedItem>recommendations = recommender.mostSimilarItems(itemID, 3);
for(RecommendedItem recommendation : recommendations){
oos.writeObject(itemID + "," + recommendation.getItemID() + "," + recommendation.getValue()+"\n");
//System.out.println(itemID + "," + recommendation.getItemID() + "," + recommendation.getValue());
}
}
} catch (IOException e) {
System.out.println("Error !");
e.printStackTrace();
} catch (TasteException e) {
System.out.println("Taste exception !");
e.printStackTrace();
}
finally {
oos.flush();
oos.close();
}
}
}
You should try FileWriter or PrintWriter
http://www.journaldev.com/878/how-to-write-a-file-in-java-using-filewriter-bufferedwriter-files-and-fileoutputstream

Read embedded Object in excel using java

I want to make one excel sheet which I need to send other for filling it.
In the excel sheet , the other person fill his information and can also attach text/doc file with excel sheet....
I need to access that text/doc file .. Please provide me a solution .
I am using Apache POI - HSSF api.
Thanks in advance.
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();
}
}
}
}
}
</code>
POI has APIs to iterate over embedded objects. (HSSFWorkbook .getAllEmbeddedObjects or XSSFWorkbook.getAllEmbedds ). Examples here http://poi.apache.org/spreadsheet/quick-guide.html#Embedded
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);
}
}
}
}
}
}

Categories

Resources