create Excel sheet between existing sheet using POI - java

I build the code to meet my client requirement using org.apache.poi.ss.usermodel.Sheet class
Now I got a new requirement to create a new excel sheet in between two existing sheets. In the existing excel file there are already three sheets at the index numbers p,1,2. I want to create a sheet at index number 2 moving the sheet at index number 2 to 3.
I could able to find the sheets names in Excel file using the code:
for (int i = 0; i < wb.getNumberOfSheets(); i++)
{
System.out.println("Sheet name: " + wb.getSheetName(i));
}
Also, I could able to find the sheet index numbres in Excel file using the code:
System.out.println("Sheet name: " + wb.getSheetIndex("Retail - All"));
The code I used to create a new sheet is: Sheet failuresSheet= wb.createSheet("Failures"); This is creating a new sheet at end. Please let me know the correct code for my requirement.
Remember that I used the class org.apache.poi.ss.usermodel.Sheet to meet my requirement.
Please let me know how to create a sheet at Index no 2 moving the sheet at index no 2 to 3. Thanks you in advance.

Look at this javadoc, you could change the shhet order with that method.
So you need:
wb.setSheetOrder("Failures",1); //the index is 0 based

Related

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.

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.

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");

Is it possible to unlock specific cells in a protected sheet (Using Aspose)

I'm using Aspose-Cells and java to export excel templates in my system.
In this particular situation I'm generating a spreadsheet where I have two sheets that I want to protect.
In one of them, I need to let the user edit only 4 cells. All the rest should be protected.
The simplest implementation should be:
protect the sheet
unlock each cell I want to let the user edit.
The problem is that I was searching to check if it's possible to do this (protect the entire sheet and unlock only a few cells) and it seems to not to be possible. Please.. tell me I'm wrong and there's a way to do this, otherwise I'll have to lock all the existing cells in the sheet and unlock only 4 of them.. For my experience using another library (PHPExcel), it seems to be very costly in terms of performance (I had to apply it for 1000 rows and more then 40 columns, so it was really costly).
It can be done easily with Aspose.Cells for Java. You can
First lock all the columns (all cells) in a worksheet
Unlock specific cells or range of cells
See the sample below.
String dataDir = "D:\\data\\";
// Create or load workbook
Workbook book = new Workbook();
// Get the first worksheet
Worksheet sheet = book.getWorksheets().get(0);
Style style;
StyleFlag flag = new StyleFlag();
// First lock all columns
for (int iCol=0 ; iCol<255 ; iCol++)
{
// Get style of the column
style = sheet.getCells().getColumns().get(iCol).getStyle();
// Apply locking to the style
style.setLocked(true);
flag.setLocked(true);
sheet.getCells().getColumns().get(iCol).applyStyle(style, flag);
}
// Get the range of cells, which we want to unlock
Range rangeUnlocked = sheet.getCells().createRange("A1:D4");
// Add a new style
int styleIndex = book.getStyles().add();
Style styleUnlocked = book.getStyles().get(styleIndex);
// Unlock cells
styleUnlocked.setLocked(false);
rangeUnlocked.setStyle(styleUnlocked);
// Protect the sheet
sheet.protect(ProtectionType.ALL);
//Save the Excel file
book.save(dataDir + "protectedrange.xlsx");
I work at Aspose as a Developer Evangelist.

Apache poi - print layout, more than one print area in the same sheet

I'm trying to develop a complex report, and I need to set up the print areas for the excel file. I must divide the xls file in 3 part, but if I do setPrintArea(..) the new area subscribe the old and the result is that I have in the print preview only the last page. How can I set more than one print area? This is the code:
protected void createCustomerSheet(String label) {
createSheet(label);
getCurrentSheet().getPrintSetup().setPaperSize(PrintSetup.A4_PAPERSIZE);
getCurrentSheet().getPrintSetup().setFitHeight((short)1);
getCurrentSheet().getPrintSetup().setFitWidth((short)1);
getCurrentSheet().setAutobreaks(true);
getCurrentSheet().setFitToPage(true);
}
then I call 3 times
wb.setPrintArea(activeSheetIndex, startColumn, endColumn, startRow, endRow);
I also tried to add break rows, but it doesn't work..
Any ideas?
Excel maintains only one print area for a spreadsheet. So Apache POI's Excel API provides the ability to set one print area.
It sounds like you might be trying to define different pages of a report. If so, you'll need to set row and/or column breaks in each Sheet in which you want this done. Use the following methods of Sheet, assuming sheet is your Sheet instance:
sheet.setAutobreaks(false);
sheet.setRowBreak(rowIndex);
sheet.setColumnBreak(columnIndex);
You may call each of those last 2 methods multiple times to establish multiple breaks.
You can set multiple print ranges like this:
try (final Workbook wb = new HSSFWorkbook(new FileInputStream("in.xls"))) {
wb.setPrintArea(0, "$E$6:$F$12,$H$16:$I$25,$J$18:$L$26");
wb.write(new FileOutputStream("out.xls"));
}
This is how I set the print area for my sheets.
// set print area
workbook.setPrintArea(
workbook.getSheetIndex(sheet.getSheetName()), //sheet index
0, //start column
x, //end column
0, //start row
i //end row
);

Categories