getting MS Excel document properties using Java - java

Please refer to the https://i.imgur.com/o8inFsx.png. The file is an MS Excel file encrypted with a password.
I am using Aspose Cell to parse this. Before I can do that, I need to get some metadata specified in the custom properties.
Is there a way to get this using Java?
In this example, I want to get "e99y" by providing "myName".
The sheet can belong to any of the users. I want to embed the property myName/e99y so the system will know which user the sheet belongs to. Then, it'll look up the correct password from the system to encrypt and open the sheet.
Thank you!

Could you try the following sample code if it works for you:
e.g
Sample code:
// Creating an XLS LoadOptions object
LoadOptions loadOptions = new LoadOptions(FileFormatType.EXCEL_97_TO_2003);
// Setting the password for the encrypted Excel file
loadOptions.setPassword("1234");
//Instantiate a Workbook object
Workbook workbook = new Workbook("C:\\book1.xls", loadOptions);
//Retrieve a list of all custom document properties of the Excel file
CustomDocumentPropertyCollection customProperties = workbook.getWorksheets().getCustomDocumentProperties();
//Accessng a custom document property by using the property name
DocumentProperty customProperty2 = customProperties.get("myName");
I am working as Support developer/ Evangelist at Aspose.

Related

Get Row and Col for embedded Object with POI

i'm currently working with Excel files (*.xlsm) and Apache POI , and i have been cracking my head over a task.
I receive some excel files that have PDFs embedded in it and i want to extract them and rename them based on the row and column they are in.
This seems weird as i know the embedded objects are represented as images ,they can occupy more than one cell and technically they are not "In" the cell.
The following code snippet lets me extract the embedded PDFs but they are named OleObject[1..2..3.etc..] wich doesnt give me any clue.
inStream = new FileInputStream(file);
XSSFWorkbook workbook = new XSSFWorkbook(inStream);
for (PackagePart pPart : workbook.getAllEmbedds()) {
String contentType = pPart.getContentType();
if (contentType.equals("application/vnd.openxmlformats-officedocument.oleObject")){
POIFSFileSystem fs = new POIFSFileSystem(pPart.getInputStream());
TikaInputStream stream = TikaInputStream.get(fs.createDocumentInputStream("CONTENTS"));
byte[] bytes = IOUtil.toByteArray(stream);
stream.close();
OutputStream outStream = new FileOutputStream(new File(ROOT_DIRECTORY.getAbsolutePath()+"\\PDF"+i+".pdf"));
IOUtil.copy(bytes, outStream);
outStream.close();
}}
I wanted to know if org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorksheet will let me see the xml code of the excell sheet and maybe eith taht i can get the info i need. Like this.
<oleObjects><mc:AlternateContent xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"><mc:Choice Requires="x14"><oleObject progId="Acrobat Document" dvAspect="DVASPECT_ICON" shapeId="1028" r:id="rId4"><objectPr defaultSize="0" r:id="rId5"><anchor moveWithCells="1"><from><xdr:col>8</xdr:col><xdr:colOff>0</xdr:colOff><xdr:row>11</xdr:row><xdr:rowOff>0</xdr:rowOff></from><to><xdr:col>8</xdr:col><xdr:colOff>1143000</xdr:colOff><xdr:row>13</xdr:row><xdr:rowOff>171450</xdr:rowOff></to></anchor></objectPr></oleObject></mc:Choice><mc:Fallback><oleObject progId="Acrobat Document" dvAspect="DVASPECT_ICON" shapeId="1028" r:id="rId4"/></mc:Fallback></mc:AlternateContent></oleObjects>
--
<objectPr defaultSize="0" r:id="rId5"><anchor moveWithCells="1"><from><xdr:col>8</xdr:col><xdr:colOff>0</xdr:colOff><xdr:row>11</xdr:row><xdr:rowOff>0</xdr:rowOff></from><to><xdr:col>8</xdr:col><xdr:colOff>1143000</xdr:colOff><xdr:row>13</xdr:row><xdr:rowOff>171450</xdr:rowOff></to></anchor></objectPr>
I guess using the anchor information would be possible but im just unable to find how to get it.
Hope this information makes things clear on what im trying to do .
Thanks in advance.
I've looked at the source code for the current poi-ooxml-schemas sources jars which you can locate here: http://repo1.maven.org/maven2/org/apache/poi/ooxml-schemas/1.3/
org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorksheet extends org.apache.xmlbeans.XmlObject which can give you the XML as a string using the inherited .toString() method. Or you can quickly access the list of OLE objects in the worksheet by calling getOleObjects() on your CTWorksheet object.
/**
* Gets the "oleObjects" element
*/
org.openxmlformats.schemas.spreadsheetml.x2006.main.CTOleObjects getOleObjects();
CTOleObjects itself extends org.apache.xmlbeans.XmlObject and again you can get the XML using toString() for parsing, or get a list of org.openxmlformats.schemas.spreadsheetml.x2006.main.CTOleObject OLE objects for iteration using CTOleObjects.getOleObjectList().
/**
* Gets a List of "oleObject" elements
*/
java.util.List<org.openxmlformats.schemas.spreadsheetml.x2006.main.CTOleObject> getOleObjectList();
CTOleObject doesn't seem to have getter methods to get the and child XML elements to allow you to determine the columns, so I think you would need to do some XML parsing, or string searching to get this info if it is contained in the string XML representation.
Hope this helps.

JXLS Set Sheet Name

I would like to provide a way for a sheet name to be specified by a command. The sheet names should be dynamically created based on the content in the sheet.
I note that it is possible to specify fixed sheet names for dynamic sheets when using the multisheet attribute of each-command.
In the version 1 documentation there is a reference to the ability to rename a sheet using ${workbook.setSheetName(0, department.name)}. Can this be used in v2? How is it supposed to work? Would workbook need to be added to the context or was it previously available?
I tried renaming the sheet in a custom command but it seems that there is too much dependence on sheet names in XlsArea for the name to be changed halfway through XlsArea.applyAt. The template sheet is not deleted and processing is not completed.
I thought about trying to get the custom command to add an area listener to change the sheet name. But the area listeners are only called on the parent area which I cannot access from within the command.
Thanks,
Wayne.
I doubt this is the correct way to do it, but til now this is the only way I've managed to do it:
Context context = PoiTransformer.createInitialContext();
Workbook workbook = WorkbookFactory.create(templateInputStream);
workbook.setSheetName(0, "newName");//Changing name of the first sheet
PoiTransformer transformer = PoiTransformer.createTransformer(workbook);
transformer.setOutputStream(resultOutputstream);
JxlsHelper.getInstance().processTemplate(context, transformer);
If you use multisheet generation feature you can just pass your own CellRefGenerator to Each-Command and create the sheet names dynamically in it.
Currently it is not possible to pass the CellRefGenerator in Excel template but it should be quite straightforward to add this functionality.
Or you can set the CellRefGenerator with Java code as shown in the documentation.
It can be done using folowing method of XLSTransformer class.
XLSTransformer transformer = new XLSTransformer();
setSpreadsheetToRename(oladSheetName, String newSheetName)

JXLS - how to create hyperlink to Excel worksheets in workbook

I am trying to create an Excel workbook with with JXLS. I want a text hyperlink for navigating through worksheets in a workbook. I couldn't find any helpful information online. Please give any idea or hyperlink for that can help to to solve the problem. Thanks
jXLS is a small and easy-to-use Java library for writing Excel files using XLS templates and reading data from Excel into Java objects using XML configuration. If you are trying to create hyerlink, jXLS doen't have low lever excel manupulation capability. But you can to use Apache POI a free library. This code create hyperlink to a Cell for that task as shown below.
//creating the cell
Row row = my_sheet.createRow(0);
Cell cell = row.createCell(0);
//creating helper class
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFCreationHelper helper= workbook.getCreationHelper();
//creating the hyperlink
link = helper.createHyperlink(HSSFHyperlink.LINK_DOCUMENT);
link.setAddress("'target_worksheet_name'!A1");
//optional hyperlink style
XSSFCellStyle hlinkstyle = workbook.createCellStyle();
XSSFFont hlinkfont = workbook.createFont();
hlinkfont.setUnderline(XSSFFont.U_SINGLE);
hlinkfont.setColor(HSSFColor.BLUE.index);
hlinkstyle.setFont(hlinkfont);
//applying the hyperlink to the cell
cell.setHyperlink(link);
jxls supports Parameterized formulas, you can probably
use cell with a formula like below
=HYPERLINK("http://test.com/", "Click ME")
Parameterize it in cell with
=HYPERLINK(${paramLink}, ${paramDisplay})
pass parameters to jxls context and they will be rendered as proper link
http://jxls.sourceforge.net/samples/param_formulas.html
Old question, but another possible solution is to use JXLS 2+ and the PoiTransformer. It has a utility class called PoiUtil which can be injected to the context.
final var transformer = PoiTransformer.createTransformer(inputStream, outputStream);
// it is important to create the context like this
// or you can manually insert the PoiUtil instance if you wish
final var context = PoiTransformer.createInitialContext();
// setup your context...
JxlsHelper.getInstance().processTemplate(context, transformer);
And in the template you can use it like this: ${util.hyperlink(linkVar, titleVar)} where the linkVar and titleVar are the corresponding variables in the context.

Hyperlink not working while populating Data into Excel

I am populating URL into Excel sheet through java code. But the hyperlink is not enabled if I populate through Java code.
If I type URL into Excel sheet directly, hyperlink automatically coming. Could you please let me know why it is not coming if I populate through code.
You may need Worksheet_followhyperlink enabled in the spreadsheet through vba. I've encountered this populating hyperlinks into Excel before. Pop this into the sheet with the links:
Private Sub Worksheet_followhyperlink(ByVal Target As Hyperlink)
Application.EnableEvents = True
Target.Follow
' Any other code you might need.
End Sub

Switching between excel sheets in Apache POI

I am using Apache POI to generate excel sheets (.xls format) and I have used the following code snippet to create Hyperlinks that link to a different sheet in the same document/workbook.
HSSFSheet summarySheet = workbook.createSheet("Target Sheet");
Hyperlink targetLink = createHelper.createHyperlink(Hyperlink.LINK_DOCUMENT);
targetLink.setAddress("'Target Sheet'!A1");
There are more than one sheet that I'm creating and upon clicking the Hyperlink it shows the respective sheet. However, I'm having difficulty in traversing to the different sheets that I have created with the above lines of code. I need to populate those sheets with data from the database but I don't know how to switch between those sheets.
Any help would be appreciated. Please do let me know before you downvote/if there is anything wrong with my question. Thank you!
To get the sheets in existing xls you can use the HSSFWORKBOOK method getSheet("Sheet Name"):
HSSFSheet linkedSheet = workbook.getSheet("Sheet name");
once you have the linked sheet you can add the entries onto it.

Categories