in excel the value of column is 10101101010000000000 but when im reading it in java using POI the value is changed to 10101101009999999000, can anyone give me an idea on whats going on and how can i get the exact values from the excel.
i've tried setting the celltype as string and use cell.getStringCellValue() and also this new BigDecimal(cell.getNumericCellValue()).toPlainString() but im still not getting the same value as with the excel
here's my code
List<BankClassVo> data = new ArrayList<BankClassVo>();
FileInputStream fis = new FileInputStream(new File(Constant.VALIDATION_REFERENCE_FILE_PATH + Constant.BANK_CLASSIFICATION_REF_FILE + ".xlsx"));
XSSFWorkbook myWorkBook = new XSSFWorkbook(fis);
XSSFSheet mySheet = myWorkBook.getSheetAt(1);
Iterator<Row> rowIterator = mySheet.iterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
BankClassVo vo = new BankClassVo ();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
if (cell.getColumnIndex() == 0) {
vo.setsClass(new BigDecimal(cell.getNumericCellValue()).toPlainString());
}
else if (cell.getColumnIndex() == 1) {
vo.setClassification(cell.getStringCellValue());
}
}
data.add(vo);
}
myWorkBook.close();
return data;
Use MathContext and RoundingMode. Ref
BigDecimal value = new BigDecimal(cell.getNumericCellValue(), new MathContext(10 , RoundingMode.CEILING));
System.out.println(value.toPlainString());
Related
I'm trying to create a Java application that can read and clean an Excel file in .xlsx format (by comparing it to a master list, also in Excel format) before writing it to a new Excel file. I also need to be able to post the cleaned file to a web app, but that's for later.
I'm using Apache POI, and have been able to successfully read the Excel file (in the output section in Eclipse it doesn't start from the first row though).
Here's where I'm stuck. I've been able to read the rows using an iterator, but how do I extract all these values to variables? Can I create a data table?
public class ReadAndCleanExcel {
public void readExcel(String filePath) {
Object[][] data = null;
final DataFormatter df = new DataFormatter();
try {
FileInputStream file = new FileInputStream(new File(filePath));
//Create Workbook instance holding reference to .xlsx file
XSSFWorkbook workbook = new XSSFWorkbook(file);
//Get first/desired sheet from the workbook
XSSFSheet sheet = workbook.getSheetAt(0);
//Iterate through each rows one by one
Iterator<Row> rowIterator = sheet.iterator();
int rownum = 0;
int colnum = 0;
Row r=rowIterator.next();
int rowcount=sheet.getLastRowNum();
int colcount=r.getPhysicalNumberOfCells();
data = new Object[rowcount][colcount];
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
//For each row, iterate through all the columns
Iterator<Cell> cellIterator = row.cellIterator();
colnum = 0;
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
//Check the cell type and format accordingly
data[rownum][colnum] = df.formatCellValue(cell);
System.out.print(df.formatCellValue(cell).toUpperCase() + " ");
colnum++;
}
rownum++;
System.out.println();
}
file.close();
workbook.close();
} catch (Exception e) {
e.printStackTrace();
}
}
I have a requirement where I have to read hindi text from an excel sheet in java. when I read the hindi text from excel and When I try to print the hindi string , only a set of ??? are displayed.
Can anyone please help me with this.
It will be really helpful. Thanks.
my code for reading --
FileInputStream inputStream = new FileInputStream(new File(excelFilePath));
XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
XSSFSheet firstSheet = workbook.getSheetAt(0);
Iterator<Row> iterator = firstSheet.iterator();
while (iterator.hasNext()) {
Row nextRow = iterator.next();
//System.out.println("nextrow"+nextRow);
Iterator<Cell> cellIterator = nextRow.cellIterator();
Cell cell = cellIterator.next();
System.out.println("Cell value =="+cell.getStringCellValue());
//System.out.print("##"+cell.getCellType());
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
Cell cell1 = cell.getRow().getCell(0);
Cell cell2 = cell.getRow().getCell(1);
System.out.println(cell1);
System.out.println(cell2);
if(cell1 != null && cell2 != null){
String col1 = cell1.getStringCellValue();
String col2 = cell2.getStringCellValue();
sentences.add(col1+"_###_"+col2);
}
break;
but when I try to print the readed data it displays ??????. please refer below -
??? ???? ????????? ?? ???????? ??? ?????? ?? ??????
I am trying to read a xlsx file with particular row number which will be provided as parameter.
I am getting NullPointerException if sheet.getRow(RowNum). I am able to read the xlsx file if i adjust column width and save it again manually. But that destroys my purpose of automation. I am able to read any other xlsx files which are created manually.
Here is the sample code :
public String readCouponCode(int getRowCount) {
try {
Registration reg=new Registration();
File inputFile = new File(this.DownloadFile);
System.out.println(DownloadFile);
// Get the workbook instance for XLSX file
XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream(inputFile));
// Get first sheet from the workbook
XSSFSheet sheet = wb.getSheetAt(0);
// Get iterator to all the rows in current sheet
Iterator<Row> rowIterator = sheet.iterator();
// Traversing over each row of XLSX file
Row row = sheet.getRow(getRowCount);
// For each row, iterate through each columns
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
int cellIndex = cell.getColumnIndex();
// System.out.println(cellIndex);
if (cellIndex == 0) {
CouponCode = cell.getStringCellValue();
System.out.println(cell.getStringCellValue() + "\t");
}
}
} catch (Exception e) {
System.err.println("Exception :" + e.getMessage());
}
return CouponCode;
}
I also tried with XSSFRow but it yields same result.
Note : I tried by commenting sheet.getRow() line and it prints only the last row. I tried to get number of rows by using sheet.getPhysicalNumberOfRows(), it gives 1 but actually my xlsx file has 7 rows.
Jars used:
dom4j poi-3.13-20150929
poi-excelant-3.13-20150929
poi-ooxml-3.13-20150929
poi-ooxml-schemas-3.13-20150929
xmlbeans-2.5.0
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()
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!