java convert HSSFCell to number - java

Could anyone help?
By using that code, I was able to get a value from an Excel field as well. There is a value for a specific column = 5.
public Integer Check4(int b) throws IOException {
InputStream myxls = new FileInputStream("book.xls");
HSSFWorkbook wb = new HSSFWorkbook(myxls);
HSSFSheet sheet = wb.getSheetAt(0); // first sheet
HSSFRow row = sheet.getRow(0); // first row
//HSSFCell cell0 = row.getCell((short)a); // first arg
HSSFCell cell1 = row.getCell((short)b); // second arg
cell1.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
System.out.println("smth "+ cell1);
return ;
}
However,
The output of the such code is:
"smth + 5.0"
I'd get it, how to convert the var cell1 5.0 to 5 ?
Math.round, Integer.parseInt() don't, actually, help

You have to get the string value from the HSSFCell before using Integer.parseInt().
Use Integer.parseInt(cell1.getStringCellValue()). You can probably use getNumericCellValue() but that will return a double.

finally, solve by (int) Math.round(cell1.getNumericCellValue()))
public Integer Check4(int b) throws IOException {
InputStream myxls = new FileInputStream("book.xls");
HSSFWorkbook wb = new HSSFWorkbook(myxls);
HSSFSheet sheet = wb.getSheetAt(0); // first sheet
HSSFRow row = sheet.getRow(1); // first row
//HSSFCell cell0 = row.getCell((short)a); // first arg
HSSFCell cell1 = row.getCell((short)b); // second arg
String sell = cell1.toString();
cell1.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
System.out.println("smth "+ (int) Math.round(cell1.getNumericCellValue()));
return (int) Math.round(cell1.getNumericCellValue());
}

Related

how to convert hssfcell to string in java

I have a piece of code which throws me (I have made the line bold)
Exception in thread "main" java.lang.ClassCastException: org.apache.poi.hssf.usermodel.HSSFCell cannot be cast to java.lang.String
at com.codi.excel.ExcelRead.main(ExcelRead.java:36)
My code is as follows -
HSSFWorkbook wb = new HSSFWorkbook(input);
HSSFSheet sheet = wb.getSheetAt(0);
List MobileSeries=new ArrayList();
MobileSeries = findRow(sheet, cellContent);
if(MobileSeries !=null){
for(Iterator iter=MobileSeries.iterator();iter.hasNext();){
**String mobileSeries=(String)iter.next();**
String LidPattern=extractNumber(mobileSeries);
if (lid.startsWith(LidPattern)) {
System.out.println("This is a mobile number");
Could you please help me out.
Apache POI provides a handy class for you to do just that - DataFormatter
Using DataFormatter, for string cells you'll get the current contents, and for numeric or date cells the value will be formatted based on the formatting / styling rules applied to the cell, then returned as a string with that applied.
To loop over all the rows and cells in a workbook, getting their values, following the pattern in the docs, just do something like:
Workbook wb = WorkbookFactory.create(input);
Sheet sheet = wb.getSheetAt(0);
DataFormatter formatter = new DataFormatter();
for (Row r : sheet) {
for (Cell c : r) {
String value = formatter.formatCellValue(c);
}
}
Easy!
While you are iterating the rows of a worksheet, check whether the HSSFCell cell is of type String or not.
InputStream fileInputStream = null;
HSSFWorkbook hssfWorkbook;
HSSFSheet sheet;
HSSFRow row;
HSSFCell cell;
Iterator rowIterator, cellIterator;
// Put these loc in a try-catch block
fileInputStream = new FileInputStream("/path/to/TestExcel.xls");
hssfWorkbook = new HSSFWorkbook(fileInputStream);
sheet = hssfWorkbook.getSheetAt(0);
rowIterator = sheet.rowIterator();
while (rowIterator.hasNext()) {
row = (HSSFRow) rowIterator.next();
cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
cell = (HSSFCell) cellIterator.next();
if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
String someVariable = cell.getStringCellValue();
} else if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
// Handle numeric type
} else {
// Handle other types
}
}
// Other code
}
Try to access cell and extract value out of it. The below snippet should help you:
Cell cell = iter.next();
cell.getStringCellValue()

How to avoid NullPointerException with an empty cell using POI?

I'm trying to get some values in my java program from an excel .xlsx file using Apache POI, but I'm having trouble because my loop encounters an empty cell sometimes, then I get a NullPointerException. How can I "test" the cell before even reading it ? Here's a piece of my code :
FileInputStream file = new FileInputStream(new File(file));
XSSFWorkbook workbook = new XSSFWorkbook(file);
XSSFSheet sheet = workbook.getSheetAt(0);
int rows;
rows = sheet.getPhysicalNumberOfRows();
for (int i=1;i<rows;i++){
Row row = sheet.getRow(i);
Cell cell = row.getCell(2); // Here is the NullPointerException
String cellString = cell.getStringCellValue();
myArrayList.add(cellString);
}
Which brings me to :
java.lang.NullPointerException
at analyse.Analyser.getExcelWords3(Analyser.java:73)
at analyse.Analyser.main(Analyser.java:21)
I want to know if there's a possibility to check if the cell is empty before trying to read it, then I won't get the NPE. Thank you in advance !
To avoid NullPointerException add this Row.MissingCellPolicy.CREATE_NULL_AS_BLANK
Cell cell = row.getCell(j, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
This will create a blank cell instead of giving you NPE
wrap your code in a try / catch statement that is what it's there for..
https://docs.oracle.com/javase/tutorial/essential/exceptions/catch.html
some untested code below to give you the idea:
for (int i=1;i<rows;i++){
try{
Row row = sheet.getRow(i);
Cell cell = row.getCell(2); // Here is the NullPointerException
String cellString = cell.getStringCellValue();
myArrayList.add(cellString);
}catch(NullPointerException NPE)
{
//what to do when the exception occurs?
}
}
Look at this method:
/**
* Returns the cell at the given (0 based) index, with the specified {#link org.apache.poi.ss.usermodel.Row.MissingCellPolicy}
*
* #return the cell at the given (0 based) index
* #throws IllegalArgumentException if cellnum < 0 or the specified MissingCellPolicy is invalid
* #see Row#RETURN_NULL_AND_BLANK
* #see Row#RETURN_BLANK_AS_NULL
* #see Row#CREATE_NULL_AS_BLANK
*/
public XSSFCell getCell(int cellnum, MissingCellPolicy policy) {
It should help you.
` FileInputStream file = new FileInputStream(new File(file));
XSSFWorkbook workbook = new XSSFWorkbook(file);
XSSFSheet sheet = workbook.getSheetAt(0);
int rows;
String cellString = null;
rows = sheet.getPhysicalNumberOfRows();
for (int i=1;i<rows;i++){
Row row = sheet.getRow(i);
if(row.getCell(2) == null)
{
cellString = null;
}
else
{
Cell cell = row.getCell(2); //if 3rd column of excelsheet then getCell(2)..
cellString = cell.getStringCellValue();
}
myArrayList.add(cellString);
}
if excel cell contain empty/blank then it will be stored as null`

java.lang.NoSuchMethodError: org.apache.poi.util.IOUtils.copy(Ljava/io/InputStream;Ljava/io/OutputStream;)V

I have program that use Apache poi 3.5
public void UploadXLSX(File file, FileType fileType)
{
XSSFWorkbook workbook = null;
XSSFSheet sheet = null;
StringBuilder query = new StringBuilder();
try {
workbook = new XSSFWorkbook(new FileInputStream(file));
sheet = workbook.getSheetAt(0);
System.out
.println("sheet.getLastRowNum() : " + sheet.getLastRowNum()
+ " First" + sheet.getFirstRowNum());
XSSFRow row; // = sheet.getRow(2); // third row
XSSFCell cell;// = row.getCell((short)3); // fourth cell
The application throw exception
java.lang.NoSuchMethodError: org.apache.poi.util.IOUtils.copy(Ljava/io/InputStream;Ljava/io/OutputStream;)V
any advice to how slove the exception
Looks like there also is an earlier version of POI on the classpath in which that method did not exist yet.
See if it helps - http://poi.apache.org/faq.html#faq-N10006

How do you get a cell's content in an Excel spreadsheet using Java? Apache POI

I'm creating a Java application that I need it to read specific cells, the cells on the document will contain Strings and some Integers. Can you please assist, I found this sample code below, but now I'm stuck. I need to persist the data on the spreadsheet to the database. Thank You
InputStream inp = new FileInputStream("workbook.xls");
//InputStream inp = new FileInputStream("workbook.xlsx");
Workbook wb = WorkbookFactory.create(inp);
Sheet sheet = wb.getSheetAt(0);
Row row = sheet.getRow(2);
Cell cell = row.getCell(3);
I changed your code to a working sample:
InputStream inp = new FileInputStream("workbook.xls");
HSSFWorkbook wb = new HSSFWorkbook(inp);
Sheet sheet = wb.getSheetAt(0);
Row row = sheet.getRow(2);
Cell cell = row.getCell(3);
if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
System.out.println("string: " + cell.getStringCellValue());
}
if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
System.out.println("numeric: " + cell.getNumericCellValue());
}
System.out.println("any: " + cell.toString());
I hope it helps!

Apache POI. Copying sheets

I'm using apache poi to create an excel document. To create new sheet in workbook I write next code:
Workbook wb = new HSSFWorkbook();
Sheet sh = wb.createSheet();
this code create and add sheet to workbook. But I want to create sheet formerly and then add it to workbook. Smth like this:
Sheet sh = new HSSFSheet();
wb.addSheet(sh);
I need such thing, because I want to copy data from one sheet of one workbook to another sheet of another workbook(Workbook interface has method Sheet cloneSheet(int)). But Workbook interface doesn't have method like addSheet(Sheet sh).
Also HSSFWorkbook is final class so I can't extend it to implement add method
How can I do this?
You can't just take a Sheet object from one Workbook, and add it to a different Workbook.
What you'll need to do is to open the old workbook and the new workbooks at the same time, and create the sheet in the new workbook. Next, clone all the styles you used in the old sheet onto the new one (HSSFCellStyle has a method for cloning a style from one workbook to another). Finally, iterate over all the cells and copy them over.
You should use RangeCopier.
XSSFWorkbook workbookFrom = new XSSFWorkbook(new File("/path/to/workbookFrom.xlsx"));
XSSFSheet sheetFrom = workbookFrom.getSheetAt(0);
XSSFWorkbook workbookTo = new XSSFWorkbook(new File("/path/to/workbookTo.xlsx"));
XSSFSheet sheetTo = workbookTo.createSheet("sheet1");
workbookTo.setSheetOrder("sheet1", 0);
XSSFRangeCopier xssfRangeCopier = new XSSFRangeCopier(sheetFrom, sheetTo);
int lastRow = sheetFrom.getLastRowNum();
int lastCol = 0;
for (int i = 0; i < lastRow; i++) {
Row row = sheetFrom.getRow(i);
if (row != null) {
if (row.getLastCellNum() > lastCol) {
lastCol = row.getLastCellNum();
}
sheetTo.setDefaultRowHeight(sheetFrom.getDefaultRowHeight());
}
}
for (int j = 0; j < lastCol; j++) {
sheetTo.setColumnWidth(j, sheetFrom.getColumnWidth(j));
}
CellRangeAddress cellAddresses = new CellRangeAddress(0, lastRow, 0, lastCol);
xssfRangeCopier.copyRange(cellAddresses, cellAddresses, true, true);
workbookTo.write(new FileOutputStream(new File("/path/to/worksheetTo.xlsx")));
POI version < v4.0
Okay I tried to do what Gagravarr said above. This solution works for me. This code will work if the sheets don't have tables, etc. If the sheets contain simple text (String, boolean, int etc), formulas, this solution will work.
Workbook oldWB = new XSSFWorkbook(new FileInputStream("C:\\input.xlsx"));
Workbook newWB = new XSSFWorkbook();
CellStyle newStyle = newWB.createCellStyle(); // Need this to copy over styles from old sheet to new sheet. Next step will be processed below
Row row;
Cell cell;
for (int i = 0; i < oldWB.getNumberOfSheets(); i++) {
XSSFSheet sheetFromOldWB = (XSSFSheet) oldWB.getSheetAt(i);
XSSFSheet sheetForNewWB = (XSSFSheet) newWB.createSheet(sheetFromOldWB.getSheetName());
for (int rowIndex = 0; rowIndex < sheetFromOldWB.getPhysicalNumberOfRows(); rowIndex++) {
row = sheetForNewWB.createRow(rowIndex); //create row in this new sheet
for (int colIndex = 0; colIndex < sheetFromOldWB.getRow(rowIndex).getPhysicalNumberOfCells(); colIndex++) {
cell = row.createCell(colIndex); //create cell in this row of this new sheet
Cell c = sheetFromOldWB.getRow(rowIndex).getCell(colIndex, Row.CREATE_NULL_AS_BLANK ); //get cell from old/original WB's sheet and when cell is null, return it as blank cells. And Blank cell will be returned as Blank cells. That will not change.
if (c.getCellType() == Cell.CELL_TYPE_BLANK){
System.out.println("This is BLANK " + ((XSSFCell) c).getReference());
}
else { //Below is where all the copying is happening. First It copies the styles of each cell and then it copies the content.
CellStyle origStyle = c.getCellStyle();
newStyle.cloneStyleFrom(origStyle);
cell.setCellStyle(newStyle);
switch (c.getCellTypeEnum()) {
case STRING:
cell.setCellValue(c.getRichStringCellValue().getString());
break;
case NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
cell.setCellValue(c.getDateCellValue());
} else {
cell.setCellValue(c.getNumericCellValue());
}
break;
case BOOLEAN:
cell.setCellValue(c.getBooleanCellValue());
break;
case FORMULA:
cell.setCellValue(c.getCellFormula());
break;
case BLANK:
cell.setCellValue("who");
break;
default:
System.out.println();
}
}
}
}
}
//Write over to the new file
FileOutputStream fileOut = new FileOutputStream("C:\\output.xlsx");
newWB.write(fileOut);
oldWB.close();
newWB.close();
fileOut.close();
If your requirement is to copy full sheets without leaving or adding anything. I think The process of elimination works better and faster then the above code. And you don't have to worry about losing formulas, drawings, tables, styles, fonts, etc.
XSSFWorkbook wb = new XSSFWorkbook("C:\\abc.xlsx");
for (int i = wb.getNumberOfSheets() - 1; i >= 0; i--) {
if (!wb.getSheetName(i).contentEquals("January")) //This is a place holder. You will insert your logic here to get the sheets that you want.
wb.removeSheetAt(i); //Just remove the sheets that don't match your criteria in the if statement above
}
FileOutputStream out = new FileOutputStream(new File("C:\\xyz.xlsx"));
wb.write(out);
out.close();
POI version >= v4.0
As of version 4.0, Cell.CELL_TYPE_BLANK and Row.CREATE_NULL_AS_BLANK don't exist (they deprecated). Use CellType.* and Row.MissingCellPolicy.* instead.

Categories