Switching between excel sheets in Apache POI - java

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.

Related

Apache POI - Applying styles per row

I am working on generating a excel in my app for reporting purposes. I can apply styles to all rows but when I try and target specific rows (as shown below), the style does not work.
public void postProcessXLS(Object document) {
HSSFWorkbook wb = (HSSFWorkbook) document;
HSSFSheet sheet = wb.getSheetAt(0);
CellStyle cs = wb.createCellStyle();
cs.setFillBackgroundColor(IndexedColors.RED1.index);
cs.setFillPattern(FillPatternType.SOLID_FOREGROUND);
cs.setFillForegroundColor(HSSFColor.HSSFColorPredefined.BLUE.getIndex());
sheet.getRow(0).setRowStyle(cs);
}
Trying to format the data in my table so the users have an easier time reading / handling it. I want to display different styles for alternate rows. If there is an easier way to do this in HSSF without having to manually write the styles, I am open to suggestions.
If you want to apply styles based on some condition or pattern , then go for conditional formatting , i faced the same challenges during my tussle with Apache POI and this post helped http://www.javavillage.in/fills-and-colors-using-conditional-formate-using-apache-poi.php , hope this helps you too

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.

Apache POI excel sheet formula reference to another sheet

I have an excel sheet which has a formula reference to another sheet of the same workbook.
Currently, I'm on Sheet 1 and trying to set a formula for a cell using cell.setFormula(Sheet2[#All]).
While I'm doing that, I'm encountering the following error :
Specified named range 'Sheet2' does not exist in the current workbook. org.apache.poi.ss.formula.FormulaParseException
at org.apache.poi.ss.formula.FormulaParser.parseNonRa nge(FormulaParser.java:569)
at org.apache.poi.ss.formula.FormulaParser.parseRange able(FormulaParser.java:429)
at org.apache.poi.ss.formula.FormulaParser.parseRange Expression(FormulaParser.java:268)
at org.apache.poi.ss.formula.FormulaParser.parseSimpl eFactor(FormulaParser.java:1119)
at org.apache.poi.ss.formula.FormulaParser.percentFac tor(FormulaParser.java:1079)
at org.apache.poi.ss.formula.FormulaParser.powerFacto r(FormulaParser.java:1066)
at org.apache.poi.ss.formula.FormulaParser.Term(Formu laParser.java:1426)
at org.apache.poi.ss.formula.FormulaParser.additiveEx pression(FormulaParser.java:1526)
at org.apache.poi.ss.formula.FormulaParser.concatExpr ession(FormulaParser.java:1510)
at org.apache.poi.ss.formula.FormulaParser.comparison Expression(FormulaParser.java:1467)
at org.apache.poi.ss.formula.FormulaParser.Arguments( FormulaParser.java:1051)
at org.apache.poi.ss.formula.FormulaParser.function(F ormulaParser.java:936)
However, in the workbook, I have created the necessary sheet. The sheet name is Sheet2. But still the code is not able to refer to that sheet. Is there a way to fix this issue or any workaround?
Sheet2 is not the same as Sheet 2. Rename Sheet 2 to Sheet2.

Apache POI - Excel Write - Lock Single Cell

I am using Apache POI to generate Exccel Templete which my clients could download, add values and upload back.
I would like to set the cell values non editable so that the template headers could not be edited.
I tried this code but it does not work,
cell.getCellStyle().setLocked(true)
I also read that locking the excel sheet and then allowing the columns to setlocked(false) would work but I am not sure how many columns will be filled by client, so I want is all other columns t be edited except the one which I filled dynamically with Apache POI.
I hope my query is clear to understand.
Try the following code, it may solve your problem:
HSSFWorkbook workbook = new XSSFWorkbook();
// Cell styles. Note the setLocked(true) method call.
HSSFCellStyle lockedNumericStyle = workbook.createCellStyle();
lockedNumericStyle.setAlignment(XSSFCellStyle.ALIGN_RIGHT);
lockedNumericStyle.setLocked(true);
HSSFSheet sheet = workbook.createSheet("Protection Test");
HSSFRow row = sheet.createRow(0);
HSSFCell cell = row.createCell(0);
cell.setCellValue(100);
cell.setCellStyle(lockedNumericStyle);
// This line should cause all locked cells to be protected,
// the user should not be able to change the cells
// contents.
sheet.protectSheet("password");
The password makes it possible to remove the protection from the sheet and makes it possible then for the locked cells to be modified.
I don't recall how well this works -- for example, I think that the client can unprotect the sheet using the menu -- but you do need to protect the sheet via something like Sheet.protectSheet("") (no password, but nevertheless a protected sheet.)

Excel generation in java

In Apache poi is there any provision for setting link between different sheets(For example i have an index page in my excel sheet which contains links to all my sheets. Can we do this for dynamic excel generation )? Is there any other libraries available for doing the same?
Yes that's possible, here is some example code:
Cell cell = sheet.createRow(0).createCell(0);
cell.setCellValue("Worksheet Link");
HSSFHyperlink link = new HSSFHyperlink(HSSFHyperlink.LINK_DOCUMENT);
link.setTextMark("'Target Sheet'!A1");
cell.setHyperlink(link);
Target Sheet is the name of the sheet to which the link should switch to and A1 is the target cell.
You can use setAddress Method also.
HSSFHyperlink linkToSheet=new HSSFHyperlink(HSSFHyperlink.LINK_DOCUMENT);
linkToSheet.setAddress("ToSheet!A115");

Categories