Page 1 of 1

Adding style part creates Exception

PostPosted: Tue Apr 12, 2011 9:41 pm
by Squ36
Hi,

I'm trying to add a styles.xml file (with all the styles I need) to the xlsx spreadsheet i'm creating, using this code :
Code: Select all
SpreadsheetMLPackage pkg = SpreadsheetMLPackage.createPackage();
factory = Context.getsmlObjectFactory();
WorksheetPart sheet = pkg.createWorksheetPart(new PartName("/xl/worksheets/sheet1.xml"), "Test Dossier", 1);

//Extract from file styles.xml
URL furl = ExcelWriter.class.getResource("styles.xml");
File knownstyles = new File(furl.toURI());
JAXBContext jc = org.docx4j.jaxb.Context.jc;
Unmarshaller u = jc.createUnmarshaller();
u.setEventHandler(new org.docx4j.jaxb.JaxbValidationEventHandler());
Styles styles = (Styles) u.unmarshal(knownstyles); //EXCEPTION THROWN HERE

pkg.addTargetPart(styles);


When I start the file creation, it throws an exception where I unmarshal. I uploaded it in a text file, because it's way too long to be put in a post.

Could you help me making this work ?
Thanks !

Re: Adding style part creates Exception

PostPosted: Wed Apr 13, 2011 1:20 am
by jason
Don't use

Code: Select all
JAXBContext jc = org.docx4j.jaxb.Context.jc;


You'd want:

Code: Select all
JAXBContext jc = org.xlsx4j.jaxb.Context.jcSML;


cheers .. Jason

Re: Adding style part creates Exception

PostPosted: Wed Apr 13, 2011 1:59 am
by Squ36
Thanks !

I finally got past this.... to get another error !!!

This line :
Code: Select all
Styles styles = (Styles) u.unmarshal(knownstyles);

produces this error during execution :
Code: Select all
javax.xml.bind.JAXBElement cannot be cast to org.docx4j.openpackaging.parts.SpreadsheetML.Styles


I believe I didn't include the right Styles class. I have this one : org.docx4j.openpackaging.parts.SpreadsheetML.Styles
The other choice (given by NetBeans) is : org.docx4j.wml.Styles, and it causes another error (before compling) on the addTargetPart method (last line of the code in my first post) :
Code: Select all
cannot find symbol
  symbol:   method addTargetPart(org.docx4j.wml.Styles)
  location: class org.docx4j.openpackaging.packages.SpreadsheetMLPackage


Could you please tell me which class to include ?
Thanks again !

Re: Adding style part creates Exception

PostPosted: Wed Apr 13, 2011 9:48 am
by jason
The part:

Code: Select all
public class Styles  extends JaxbSmlPart<CTStylesheet>


So you want CTStylesheet.

But your unmarshalled object is wrapped in a JAXBElement (JAXB does that for some things in the schemas), so you'll need something like:

Code: Select all
CTStylesheet stylesheet = (CTStylesheet )((JAXBElement)u.unmarshal(knownstyles)).getValue();

Re: Adding style part creates Exception

PostPosted: Wed Apr 13, 2011 7:42 pm
by Squ36
Thanks for your answer !
I finally sorted it out without banging my head on the wall like I had planned :D