In Excel file , How to set cell name using Java - java

I have an excel file. I want to set a unique name to a particular cell.
But there is no method called "cell.setName".

Regarding official documentation:
Named Range is a way to refer to a group of cells by a name. Named Cell is a degenerate case of Named Range in that the 'group of cells' contains exactly one cell. You can create as well as refer to cells in a workbook by their named range. When working with Named Ranges, the classes org.apache.poi.ss.util.CellReference and org.apache.poi.ss.util.AreaReference are used.
Note: Using relative values like 'A1:B1' can lead to unexpected moving of the cell that the name points to when working with the workbook in Microsoft Excel, usually using absolute references like '$A$1:$B$1' avoids this, see also this discussion.
Creating Named Range / Named Cell
// setup code
String sname = "TestSheet", cname = "TestName", cvalue = "TestVal";
Workbook wb = new HSSFWorkbook();
Sheet sheet = wb.createSheet(sname);
sheet.createRow(0).createCell(0).setCellValue(cvalue);
// 1. create named range for a single cell using areareference
Name namedCell = wb.createName();
namedCell.setNameName(cname + "1");
String reference = sname+"!$A$1:$A$1"; // area reference
namedCell.setRefersToFormula(reference);
// 2. create named range for a single cell using cellreference
Name namedCel2 = wb.createName();
namedCel2.setNameName(cname + "2");
reference = sname+"!$A$1"; // cell reference
namedCel2.setRefersToFormula(reference);
// 3. create named range for an area using AreaReference
Name namedCel3 = wb.createName();
namedCel3.setNameName(cname + "3");
reference = sname+"!$A$1:$C$5"; // area reference
namedCel3.setRefersToFormula(reference);
// 4. create named formula
Name namedCel4 = wb.createName();
namedCel4.setNameName("my_sum");
namedCel4.setRefersToFormula("SUM(" + sname + "!$I$2:$I$6)");
Link: https://poi.apache.org/components/spreadsheet/quick-guide.html#NamedRanges

// setup code
String sname = "TestSheet", cname = "TestName", cvalue = "TestVal";
Workbook wb = new HSSFWorkbook();
Sheet sheet = wb.createSheet(sname);
sheet.createRow(0).createCell((short) 0).setCellValue(cvalue);
// 1. create named range for a single cell using areareference
Name namedCell = wb.createName();
namedCell.setNameName(cname);
String reference = sname+"!A1:A1"; // area reference
namedCell.setRefersToFormula(reference);
From : http://poi.apache.org/components/spreadsheet/quick-guide.html#NamedRanges

Related

Select specific range/scope of a pivot table to apply format on (Aspose.Cells for Java)

Is there an equivalent of this VBA function PivotTable.PivotSelect in Aspose.Cells product ?
I am looking for a way to create a border on a whole selection of cells containing specific data field values, or on a specific scope as you prefer.
The VBA macro to perform this action is the following, by giving only the data field name parameter :
v_wbx.Sheets(v_SheetName).**PivotTables(v_CurrentPivotName).PivotSelect **DataFieldName**, xlDataAndLabel, True**
Selection.Borders(xlDiagonalDown).LineStyle = xlNone
Selection.Borders(xlDiagonalUp).LineStyle = xlNone
With Selection.Borders(xlEdgeLeft)
.LineStyle = xlContinuous
.Color = v_Color
.TintAndShade = 0
.Weight = v_Weight
End With
With Selection.Borders(xlEdgeTop)
.LineStyle = xlContinuous
.Color = v_Color
.TintAndShade = 0
.Weight = v_Weight
End With
With Selection.Borders(xlEdgeBottom)
.LineStyle = xlContinuous
.Color = v_Color
.TintAndShade = 0
.Weight = v_Weight
End With
With Selection.Borders(xlEdgeRight)
.LineStyle = xlContinuous
.Color = v_Color
.TintAndShade = 0
.Weight = v_Weight
End With
Is this covered by Aspose.Cells ? I looked into documentation but haven't found any solution.
I'm aware that the "scope" selection is available with the Aspose conditional formatting, but here I want to create the border around the WHOLE selection of cells by specifying the data field name, and NOT use any Conditional Format rule.
This is done via VBA using this enum : https://learn.microsoft.com/en-us/office/vba/api/excel.xlptselectionmode and the function mentioned before.
I precise I'm using the trial version of the product to evaluate the range of features.
Please share your positive or negative feedback on this topic, thank you
You can format specific data area values in the Pivot Table via Aspose.Cells for Java. See the following example for your reference. You can apply formatting via both ways (i.e., use directly apply formatting and via pivot format condition).
e.g.
Sample code:
//Instantiating a Workbook object
Workbook workbook = new Workbook();
//Obtaining the reference of the newly added worksheet
int sheetIndex = workbook.getWorksheets().add();
Worksheet sheet = workbook.getWorksheets().get(sheetIndex);
Cells cells = sheet.getCells();
//Setting the value to the cells
Cell cell = cells.get("A1");
cell.setValue("Sport");
cell = cells.get("B1");
cell.setValue("Quarter");
cell = cells.get("C1");
cell.setValue("Sales");
cell = cells.get("A2");
cell.setValue("Golf");
cell = cells.get("A3");
cell.setValue("Golf");
cell = cells.get("A4");
cell.setValue("Tennis");
cell = cells.get("A5");
cell.setValue("Tennis");
cell = cells.get("A6");
cell.setValue("Tennis");
cell = cells.get("A7");
cell.setValue("Tennis");
cell = cells.get("A8");
cell.setValue("Golf");
cell = cells.get("B2");
cell.setValue("Qtr3");
cell = cells.get("B3");
cell.setValue("Qtr4");
cell = cells.get("B4");
cell.setValue("Qtr3");
cell = cells.get("B5");
cell.setValue("Qtr4");
cell = cells.get("B6");
cell.setValue("Qtr3");
cell = cells.get("B7");
cell.setValue("Qtr4");
cell = cells.get("B8");
cell.setValue("Qtr3");
cell = cells.get("C2");
cell.setValue(1500);
cell = cells.get("C3");
cell.setValue(2000);
cell = cells.get("C4");
cell.setValue(600);
cell = cells.get("C5");
cell.setValue(1500);
cell = cells.get("C6");
cell.setValue(4070);
cell = cells.get("C7");
cell.setValue(5000);
cell = cells.get("C8");
cell.setValue(6430);
PivotTableCollection pivotTables = sheet.getPivotTables();
//Adding a PivotTable to the worksheet
int index = pivotTables.add("=A1:C8", "E3", "PivotTable2");
//Accessing the instance of the newly added PivotTable
PivotTable pivotTable = pivotTables.get(index);
//Unshowing grand totals for rows.
pivotTable.setRowGrand(false);
//Dragging the first field to the row area.
pivotTable.addFieldToArea(PivotFieldType.ROW, 0);
//Dragging the second field to the column area.
pivotTable.addFieldToArea(PivotFieldType.COLUMN, 1);
//Dragging the third field to the data area.
pivotTable.addFieldToArea(PivotFieldType.DATA, 2);
pivotTable.refreshData();
pivotTable.calculateData();
/*
//Apply formatting to specific data area values via Pivot format condition.
PivotFormatConditionCollection pfcc = pivotTable.getPivotFormatConditions();
int pIndex = pfcc.add();
PivotFormatCondition pfc = pfcc.get(pIndex);
FormatConditionCollection fcc = pfc.getFormatConditions();
CellArea dataBodyRange = pivotTable.getDataBodyRange();
fcc.addArea(dataBodyRange);
int idx = fcc.addCondition(FormatConditionType.CELL_VALUE);
FormatCondition fc = fcc.get(idx);
fc.setFormula1("6000");
fc.setOperator(OperatorType.GREATER_OR_EQUAL);
//fc.getStyle().setBackgroundColor(com.aspose.cells.Color.getRed());
fc.getStyle().setBorder(BorderType.LEFT_BORDER, CellBorderType.THICK, com.aspose.cells.Color.getRed());
fc.getStyle().setBorder(BorderType.TOP_BORDER, CellBorderType.THICK, com.aspose.cells.Color.getRed());
fc.getStyle().setBorder(BorderType.RIGHT_BORDER, CellBorderType.THICK, com.aspose.cells.Color.getRed());
fc.getStyle().setBorder(BorderType.BOTTOM_BORDER, CellBorderType.THICK, com.aspose.cells.Color.getRed());
*/
///*
//Apply formatting directly to specific data fields.
CellArea dataArea = pivotTable.getDataBodyRange();
for(int dataRowNum = dataArea.StartRow; dataRowNum <= dataArea.EndRow;dataRowNum++){
for(int dataColNum = dataArea.StartColumn;dataColNum <= dataArea.EndColumn;dataColNum++){
cell = cells.get(dataRowNum,dataColNum);
int value = cell.getIntValue();
System.out.println(value);
if (value > 6000) {
Style style = cell.getStyle();
com.aspose.cells.Font font = style.getFont();
font.setColor(com.aspose.cells.Color.getBlue());
style.setBorder(BorderType.LEFT_BORDER, CellBorderType.THICK, com.aspose.cells.Color.getRed());
style.setBorder(BorderType.TOP_BORDER, CellBorderType.THICK, com.aspose.cells.Color.getRed());
style.setBorder(BorderType.RIGHT_BORDER, CellBorderType.THICK, com.aspose.cells.Color.getRed());
style.setBorder(BorderType.BOTTOM_BORDER, CellBorderType.THICK, com.aspose.cells.Color.getRed());
pivotTable.format(dataRowNum, dataColNum, style);
}
}
}
workbook.save("f:\\files\\out1.xlsx");
You may also post your queries in the dedicated forum.
PS. I am working as Support developer/ Evangelist at Aspose.

Java Apache Poi Write Excel

I working in an application in Java to write to an excel. I am using apache poi libraries. I have a requirement to create pivot table. I am able to create pivot table and sum the columns using below code.
CellReference topLeft = new CellReference(0, 0);
CellReference bottomRight = new CellReference(10, 3);
AreaReference aref = new AreaReference(topLeft, bottomRight);
CellReference pos = new CellReference(0, 0);
XSSFSheet pivotSheet = workbook.createSheet("PivotSheet");
XSSFPivotTable pivotTable = pivotSheet.createPivotTable(aref,pos,dataSheet)
pivotOrgWiseSheet.setDisplayGridlines(true);
pivotTable.addRowLabel(0);
pivotTable.addRowLabel(1);
pivotTable.addColumnLabel(DataConsolidateFunction.SUM, 2, "Sum of column3");
pivotTable.addColumnLabel(DataConsolidateFunction.SUM, 3, "Sum of column4");
But the above code generate excel like
But I am not sure why the keyword "values" comes in 2nd column header and also is it possible to change the value "Row Label" to custom text like "Category"
I want it something like below.
I am not sure how to remove the keyword "Values", but I guess to change the header to custom string, we have to get the value and set it out ?
In Excel there is a setting Field Headers on the Analyze or Options tab, in the Show group. This switches between showing and hiding field headers.
See Change the layout of columns, rows, and subtotals.
The corresponding setting in org.openxmlformats.schemas.spreadsheetml.x2006.main.CTPivotTableDefinition is setShowHeaders.
So
...
pivotTable.getCTPivotTableDefinition().setShowHeaders(false);
...
should hiding field headers in your pivot table.
But your picture of the wanted result looks more as if the data headers are visible but the RowHeaderCaption was changed and first row containing the DataCaption is hidden. That would be:
...
//pivotTable.getCTPivotTableDefinition().setShowHeaders(false);
pivotTable.getCTPivotTableDefinition().setRowHeaderCaption("Category");
pivotTable.getCTPivotTableDefinition().setDataCaption("Changed Data Caption");
CellUtil.getRow(pos.getRow(), pivotSheet).setZeroHeight(true);
...

Splitting rows of Nested Table OR Inner Table using iTextPDF

How do I split the rows of the inner table. Problem description according to the image.
Here, I have table named PARENT_TABLE that has cell that contains two tables named HEADER_TABLE and CONTENT_TABLE
CONTENT_TABLE has a cell that contains INNER_TABLE. INNER_TABLE contains the dynamic rows/content whose height will be changed according to content.
So, If I make this table using one page it's working perfectly. But incase if I need to split the table in different pages it shows the error like image_2. Please help me out. As a result: The table should look like in the image_1 even if the page split into two or more pages.
Please checkout mentioned image to be more clear.
image_1
Attempt to read from field 'float com.itextpdf.text.pdf.ColumnText.maxY' on a null object reference
image_2
I just found out the solution. The issue occurs only in the case when trying to split the PDFPTable into two pages. I had used tableCell.setRowspan(2), so when trying to split the table above issue occurs.
SOLVED IT: I just made an empty cell in place of using tableCell.setRowspan(2).
private PdfPTable contentWithDateTitleAndDescription(String stringData1, String stringData2, String stringData3, String stringData4) throws IOException, BadElementException {
float relativeWidth[] = {2, 7};
PdfPTable table = new PdfPTable(relativeWidth);
table.setWidthPercentage(100);
PdfPCell cellA = new PdfPCell();
cellA.setBorder(Rectangle.NO_BORDER);
// dateCell.setRowspan(2);
cellA.setPaddingLeft(15);
cellA.setVerticalAlignment(Element.ALIGN_CENTER);
cellA.setPaddingTop(7);
Paragraph dateParagraph = new Paragraph(stringData1);
cellA.addElement(dateParagraph);
PdfPCell emptyCellB = new PdfPCell();
emptyCellB.setBorder(Rectangle.NO_BORDER);
PdfPCell cellC = new PdfPCell();
cellC.setBorder(Rectangle.NO_BORDER);
cellC.setVerticalAlignment(Element.ALIGN_LEFT);
Paragraph titleParagraph = new Paragraph(stringData2 + " / " + stringData3);
cellC.addElement(titleParagraph);
PdfPCell cellD = new PdfPCell();
cellD.setBorder(Rectangle.NO_BORDER);
cellD.setVerticalAlignment(Element.ALIGN_LEFT);
Paragraph descriptionParagraph = new Paragraph(stringData4);
cellD.addElement(descriptionParagraph);
cellD.setPaddingBottom(15);
table.addCell(cellA);
table.addCell(cellC);
table.addCell(emptyCellB);
table.addCell(cellD);
return table;
}

Apache POI : Update cells in a named range

I am using Apache POI library to read/write to xlsx. In my original xlsx, I have a namedrange "XYZ".
I want to update the values of cells within this name range. How can I do that?
I did this:
XSSFName name = workbook.getName("XYZ");
String formula = name.getRefersToFormula();
System.out.println("Formula = " + formula);
Now, I dont know how to get a handle to individual cell in this named range.
Can anyone please point me to the correct API that I can use?
Rgds
Sapan
There is an example from the Busy Developers' Guide for retrieving the cells in the range. Then you can use Cell.setCellValue() to update.
// setup code
String cname = "TestName";
Workbook wb = getMyWorkbook(); // retrieve workbook
// retrieve the named range
int namedCellIdx = wb.getNameIndex(cname);
Name aNamedCell = wb.getNameAt(namedCellIdx);
// retrieve the cell at the named range and test its contents
AreaReference aref = new AreaReference(aNamedCell.getRefersToFormula());
CellReference[] crefs = aref.getAllReferencedCells();
for (int i=0; i<crefs.length; i++) {
Sheet s = wb.getSheet(crefs[i].getSheetName());
Row r = s.getRow(crefs[i].getRow());
Cell c = r.getCell(crefs[i].getCol());
// extract the cell contents based on cell type etc.
}

Create dataValidation from named list in different sheet

i'm trying to create a dataValidation object with a List Constraint being the name of a ranged single contiguous column .... The list which i would pass on as argument to the createFormulaListConstraint() is in a different sheet than where i would like to display the dataValidation.
The following is the code that i have so far and when i try to run it a FormulaParseException: Specified name range does not exist in the current workbook is being thrown:
Name name = dctmWorkSheet.getWorkbook().createName();
name.setSheetIndex(1);
name.setNameName(cell.getStringCellValue());
name.setRefersToFormula(getRangeRefersToFormula(valueAssSheet, firstRow, rowIndex, insertCol));
validationHelper = dctmWorkSheet.getDataValidationHelper();
//------ THIS IS THE LINE RESPONSIBLE FOR THE EXCEPTION -------
constraint = validationHelper.createFormulaListConstraint(name.getNameName());
dataValidation = validationHelper.createValidation(constraint, cral);
dataValidation.setEmptyCellAllowed(true);
dataValidation.setShowErrorBox(true);
dataValidation.setErrorStyle(DataValidation.ErrorStyle.STOP);
dataValidation.createErrorBox("Error", "Please use Pick List Value");
dctmWorkSheet.addValidationData(dataValidation);
Thanks for any help or feedback......
Actually managed to solve my problem by creating an additional name to sheetIndex(0) and reference it to the name in sheetIndex(1)....
The following is the code which works as desired:
Name name = dctmWorkSheet.getWorkbook().createName();
name.setSheetIndex(1);
name.setNameName(cell.getStringCellValue());
name.setRefersToFormula(getRangeRefersToFormula(valueAssSheet, firstRow, rowIndex, insertCol));
Name name2 = dctmWorkSheet.getWorkbook().createName();
name2.setSheetIndex(0);
name2.setNameName(name.getNameName());
name2.setRefersToFormula(name.getRefersToFormula());
validationHelper = dctmWorkSheet.getDataValidationHelper();
constraint = validationHelper.createFormulaListConstraint(name2.getNameName());
dataValidation = validationHelper.createValidation(constraint, cral);
dataValidation.setEmptyCellAllowed(true);
dataValidation.setShowErrorBox(true);
dataValidation.setErrorStyle(DataValidation.ErrorStyle.STOP);
dataValidation.createErrorBox("Error", "Please use Pick List Value");
dctmWorkSheet.addValidationData(dataValidation);

Categories