Writing to a particular cell location using Apache POI Excel - java

If I've got an list of parameters 'x,y,z' that aren't sorted, is there a straightforward way to write them to particular cells in an excel document created with POI, as though the first two parameters are X and Y coordinates?
For example, I have rows like:
10,4,100
Is it possible to write the value '100' in the cell at the 10th row, 4th column?
Looking at the documentation, it looks straightforward to iterate values into the next row, but I can't see any way of creating a fixed number of rows and columns and writing particular values to only certain cells.
Any advice or suggestions would be appreciated, thanks!

Sure, it's very easy, just remember that POI is 0 based not 1 based in addressing. Assuming you want to write to the 10th row, 4th column, you'd do something like
Row r = sheet.getRow(9); // 10-1
if (r == null) {
// First cell in the row, create
r = sheet.createRow(9);
}
Cell c = r.getCell(3); // 4-1
if (c == null) {
// New cell
c = r.createCell(3, Cell.CELL_TYPE_NUMERIC);
}
c.setCellValue(100);

Related

Aspose Cells for Java: get original CSV row

I am using Aspose to read a CSV file.
I do not beforehand know the number of cells for each row of the file, but I will need to know it for further processing.
Unfortunately, I see no way to find out the number of cells in a CSV row.
Imagine the following row in the CSV file. It contains 7 cells, 4 of which are empty:
1,2,,4,,,
Using
row.iterator();
Aspose will only return 3 cells, as it ignores all empty cells.
As an alternative, I now do the following:
Cell lastCell = row.getLastCell();
int count = 0;
do {
cell = row.getCellOrNull(count);
String cellValue = cell == null ? "" : cell.getStringValueWithoutFormat();
//do something with the cell value...
count++;
} while (cell == null || ! lastCell.equals(cell));
This works better, as it returns the first 4 cells.
However, it still ignores the last 3 cells .
Is there any way to get information about the missing cells?
(It would be sufficient for me if Aspose could return the original Row as a String - I could then count the number of commas and find out the number of cells this way)
You may use Worksheet.getCells().getMaxDisplayRange() method to get the maximum display range.
Please consider this CSV. If you open it in MS-Excel and check the last cell, you will find it is Q2
Book1.csv
2,,,,1,,,,,,,,,,,,,
,,3,,,,
Aspose.Cells returns the same via the following code.
TxtLoadOptions opts = new TxtLoadOptions(LoadFormat.CSV);
Workbook wb = new Workbook("Book1.csv", opts);
Worksheet ws = wb.getWorksheets().get(0);
Range rng = ws.getCells().getMaxDisplayRange();
System.out.println(rng);
Here is the console output of the code.
Console Output
Aspose.Cells.Range [ Sheet1!A1:Q2 ]
Note: I am working as Developer Evangelist at Aspose

Apache POI : Why data is not properly inserted?

I want to insert a string to a Matrix of Cells in Excel, Using Apache POI, Here is the code :
for (int j=0;j<13;j++){
for(int i=6;i<30;i++)
{
XSSFRow row=sheet6.createRow(i);
cell0=row.createCell(j);
cell0.setCellValue("SampleRules_CI_01");
}
}
After executing my program, I get the column j=12 correctly filled, but the other columns (from 0 to 11) are still empty
You are replacing the row each time you get back around to the same value of i, when you call the createRow method. This has the effect of erasing whatever was on that row already, and only the last column doesn't get erased this way.
First, inside your i for loop, call the getRow method to see if it already exists. If it returns null, then the row doesn't exist yet and then you can call createRow.
XSSFRow row = sheet6.getRow(i);
if (row == null)
{
row = sheet6.createRow(i);
}

Need help regarding array formulas implementation in apache poi api

I got allocated updation of existing project. Previous developer used jcom api to export data to excel sheets. But jcom api don't work with 64 bit systems. I decided to change code and using apache poi api. I managed to done many methods. My problem is array formulas. I Need to implement array formulas using apache poi. Those formulas are posted below, any help will be more appreciable. Thanks in advance guys.
Formulas:
String formula1 = "SUM(R[-2]C/1.200)";//net income calculation from gross income
String formula2 = "SUM(R[-1]C-R[1]C)";
String formula3 = "SUM(R[-" + Integer.toString(listTypeTotals.size()+1) + "]C:R[-2]C)";
I tried to set that cell as formulatype and passing formula as string.
setCellFormulaStyle(sheet, 4, i+2, formula2);
public static void setCellFormulaStyle(HSSFSheet sheet,int row, int column,String value)
{
HSSFRow temprow = null;
temprow =getRow_CreateRow(sheet, row);
temprow.createCell(column).setCellFormula(value);
}
public static HSSFRow getRow_CreateRow(HSSFSheet sheet,int row)
{
HSSFRow excelrow=null;
excelrow = sheet.getRow(row);
if(excelrow==null)
{
excelrow =sheet.createRow(row);
return excelrow;
}else
return excelrow;
}
I am getting following exception
org.apache.poi.ss.formula.FormulaParseException: Specified named range 'R' does not exist in the current workbook.
at org.apache.poi.ss.formula.FormulaParser.parseNonRange(FormulaParser.java:569)
at org.apache.poi.ss.formula.FormulaParser.parseRangeable(FormulaParser.java:517)
at org.apache.poi.ss.formula.FormulaParser.parseRangeExpression(FormulaParser.java:268)
at org.apache.poi.ss.formula.FormulaParser.parseSimpleFactor(FormulaParser.java:1119)
at org.apache.poi.ss.formula.FormulaParser.percentFactor(FormulaParser.java:1079)
at org.apache.poi.ss.formula.FormulaParser.powerFactor(FormulaParser.java:1066)
at org.apache.poi.ss.formula.FormulaParser.Term(FormulaParser.java:1426)
at org.apache.poi.ss.formula.FormulaParser.additiveExpression(FormulaParser.java:1526)
at org.apache.poi.ss.formula.FormulaParser.concatExpression(FormulaParser.java:1510)
at org.apache.poi.ss.formula.FormulaParser.comparisonExpression(FormulaParser.java:1467)
at org.apache.poi.ss.formula.FormulaParser.Arguments(FormulaParser.java:1051)
at org.apache.poi.ss.formula.FormulaParser.function(FormulaParser.java:936)
at org.apache.poi.ss.formula.FormulaParser.parseNonRange(FormulaParser.java:558)
at org.apache.poi.ss.formula.FormulaParser.parseRangeable(FormulaParser.java:429)
at org.apache.poi.ss.formula.FormulaParser.parseRangeExpression(FormulaParser.java:268)
at org.apache.poi.ss.formula.FormulaParser.parseSimpleFactor(FormulaParser.java:1119)
at org.apache.poi.ss.formula.FormulaParser.percentFactor(FormulaParser.java:1079)
at org.apache.poi.ss.formula.FormulaParser.powerFactor(FormulaParser.java:1066)
at org.apache.poi.ss.formula.FormulaParser.Term(FormulaParser.java:1426)
at org.apache.poi.ss.formula.FormulaParser.additiveExpression(FormulaParser.java:1526)
at org.apache.poi.ss.formula.FormulaParser.concatExpression(FormulaParser.java:1510)
at org.apache.poi.ss.formula.FormulaParser.comparisonExpression(FormulaParser.java:1467)
at org.apache.poi.ss.formula.FormulaParser.unionExpression(FormulaParser.java:1447)
at org.apache.poi.ss.formula.FormulaParser.parse(FormulaParser.java:1568)
at org.apache.poi.ss.formula.FormulaParser.parse(FormulaParser.java:176)
at org.apache.poi.hssf.model.HSSFFormulaParser.parse(HSSFFormulaParser.java:72)
at org.apache.poi.hssf.usermodel.HSSFCell.setCellFormula(HSSFCell.java:594)`
I am not sure how you have use the formula yet. However if your problem is regarding the dynamic cell reference based on rows and Columns, perhaps I can help you.
For any cell, say "B5", at runtime,
cell.getReference();
will give you cell reference (like in example... it will return you "B5"
cell.getReference().toString().charAt(0);
will give you the Column Reference (will give you "B" if the current cell is B5). Now
cell.getRowIndex();
OR
cell.getReference().toString().charAt(1);
will give you Row Index. I have used that multiple times to update/create the Named ranges and formula on my workbook.
Small Changes to include handling address like AZ89
For the cases of AZ99 we can use for this we can use small hacks like:
String str = cell.getReference();
for(index = 0;index<str.length();index++){
if((int)str.charAt(index)<65){
break;
}
}
String Col = str.substring(0, index);
String Row = str.substring(index+1, str.length());

Get Cell by a Cell reference letter identifier with Apache POI

I am trying to get the Cell from the Row by a Cell reference and I have a problem. For example I have:
row.getCell(CellReference.convertColStringToIndex("B"));
That works fine if the Column index is 1, but if Column was deleted so the B Column index became 2 and the method: CellReference.convertColStringToIndex("B") is still converting it to 1 in which case I can't get my Column, I am getting null.
So the question is how can I get the Column from the Row depending on Cell identifier which is a letter?
Take a look at my answer to a previous question:
You probably want to use the CellReference utility class to help you out. It offers conversion between Excel style letter+number references, and POI style 0-based rows+columns. When using it, you can do something like:
Sheet sheet = workbook.getSheet("MyInterestingSheet");
CellReference ref = new CellReference("B12");
Row r = sheet.getRow(ref.getRow());
if (r != null) {
Cell c = r.getCell(ref.getCol());
}
That will let you find the cell at a given Excel-style reference (if it's defined, else null)

How to add multiple different columns of excel using Apache POI & Java

I need to generate CodeKey that is combination of two columns of excel value and values in those columns can be Boolean, String, Numeric or combination of all of those.
Now I can go through if/else loop and check for every condition but what would be an efficient way of doing this.
For Example:
If i have ExCode = 7V and PrCode = A: then my CodeKey should be 7VA:
ExCode PrCode
6D: A:
6R TR
7V 6K
And all i want to do is generate CodeKey as 6D:A:, 6RTR and 7V6K respectively.
Don't want to do something like:
if(ExCodeCellValue.getCellType() == Cell.CELL_TYPE_STRING &&
PrCodeCellValue.getCellType() == Cell.CELL_TYPE_STRING){
System.out.println("Combined String Values: "+ExCodeCellValue.getStringValue()+PrCodeCellValue.getStringValue());
}
As there would be lots of if/else unnecessary stuffs to generate codeKey, any other efficient solution of doing this or is there any api in POI that would be useful for this case?
I think you should be able to use DataFormatter.formatCellValue(cell) which will give you a string that matches what Excel shows for a cell.
With that, you could would look something like (Assuming the ExCode is the 3rd column, PrCode in the 4th)
// Do this once
DataFormatter formatter = new DataFormatter();
// Once per row
for (Row row : sheet) {
String exCode = formatter.formatCellValue( row.getCell(2) );
String prCode = formatter.formatCellValue( row.getCell(3) );
Cell code = row.createCell(4, Cell.CELL_TYPE_STRING);
code.setCellValue(exCode + prCode);
}

Categories