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()
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 written a program that reads Excel template sheet. In which the first column was hidden. Now, I have a code that un-hide the excel column programmatically (so Column start from A1).
I'm using Apache POI 3.16 version.
When I open a file, it should show me a column from A1 instead it shows me from B1 column.
When I write below code for XLS, It working properly but didn't work for an XLSX format.
sheet.showInPane(0, 0);
I need to manually move the horizontal scroll bar to view my first column. How should I achieve this programmatically to auto-scroll to the first column for XLSX format?
Here is my full code.
public Workbook readWorkBookAndWriteErrors(String bufId,String inputFile, String ext) throws Exception {
Workbook workBook =null;
Sheet sheet = null;
if(GlobalVariables.EXCEL_FORMAT_XLS.equalsIgnoreCase(ext)){
// Get the workbook instance for XLS file
workBook = new HSSFWorkbook(new FileInputStream(inputFile));
}else{
// Get the workbook instance for XLSX file
workBook = new XSSFWorkbook(new FileInputStream(inputFile));
}
sheet = workBook.getSheetAt(0);
Row row = null;
if(sheet.isColumnHidden(0)){
sheet.setColumnHidden(0, false);
sheet.setActiveCell(new CellAddress("A1"));
sheet.showInPane(0, 0);
sheet.createFreezePane(0, 1);
Iterator<Row> rowIterator = sheet.iterator();
int rowIndex = 1;
while (rowIterator.hasNext()) {
row = rowIterator.next();
if(rowIndex == 1){
rowIndex++;
continue;
}
Cell cell = row.createCell(0);
cell.setCellValue("error message");
rowIndex++;
}
}
return workBook;
}
Here is the answer to my question. Please refer this Source
public Workbook readWorkBookAndWriteErrors(String bufId,String inputFile, String ext) throws Exception {
Workbook workBook =null;
Sheet sheet = null;
if(GlobalVariables.EXCEL_FORMAT_XLS.equalsIgnoreCase(ext)){
// Get the workbook instance for XLS file
workBook = new HSSFWorkbook(new FileInputStream(inputFile));
}else{
// Get the workbook instance for XLSX file
workBook = new XSSFWorkbook(new FileInputStream(inputFile));
}
sheet = workBook.getSheetAt(0);
Row row = null;
if(sheet.isColumnHidden(0)){
sheet.setColumnHidden(0, false);
if(sheet instanceof XSSFSheet){
CTWorksheet ctWorksheet = null;
CTSheetViews ctSheetViews = null;
CTSheetView ctSheetView = null;
XSSFSheet tempSheet = (XSSFSheet) sheet;
// First step is to get at the CTWorksheet bean underlying the worksheet.
ctWorksheet = tempSheet.getCTWorksheet();
// From the CTWorksheet, get at the sheet views.
ctSheetViews = ctWorksheet.getSheetViews();
// Grab a single sheet view from that array
ctSheetView = ctSheetViews.getSheetViewArray(ctSheetViews.sizeOfSheetViewArray() - 1);
// Se the address of the top left hand cell.
ctSheetView.setTopLeftCell("A1");
}else{
sheet.setActiveCell(new CellAddress("A1"));
sheet.showInPane(0, 0);
}
Iterator<Row> rowIterator = sheet.iterator();
int rowIndex = 1;
while (rowIterator.hasNext()) {
row = rowIterator.next();
if(rowIndex == 1){
rowIndex++;
continue;
}
Cell cell = row.createCell(0);
cell.setCellValue("error message");
rowIndex++;
}
}
return workBook;
}
If you are using latest C# NPOI, I made this utility function:
/// <summary>Set view position at given coordinates.</summary>
/// <param name="sheet">A reference to the Excel sheet.</param>
/// <param name="topLeftCell">The coordinates of the cell that will show in top left corner when you open the Excel sheet (example: "A1").</param>
/// <param name="onlyFirstView">If true, only first sheet view will have position adjusted. If false, every views from the sheet will have have position adjusted.</param>
public static void SetViewPosition(ref NPOI.SS.UserModel.ISheet sheet, string topLeftCell = "A1", bool onlyFirstView = true)
{
NPOI.OpenXmlFormats.Spreadsheet.CT_Worksheet worksheet = (NPOI.OpenXmlFormats.Spreadsheet.CT_Worksheet)(typeof(NPOI.XSSF.UserModel.XSSFSheet).GetField("worksheet", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)?.GetValue((NPOI.XSSF.UserModel.XSSFSheet)sheet));
if (worksheet?.sheetViews?.sheetView != null && worksheet.sheetViews.sheetView.Count > 0)
{
if (onlyFirstView)
worksheet.sheetViews.sheetView[0].topLeftCell = topLeftCell;
else
foreach (NPOI.OpenXmlFormats.Spreadsheet.CT_SheetView view in worksheet.sheetViews.sheetView)
view.topLeftCell = topLeftCell;
}
}
Usage example:
NPOI.SS.UserModel.ISheet mySheet = myWorkbook.GetSheetAt(0);
// First sheet from our workbook opens with view set to top left corner (cell A1 visible in top left corner).
SetViewPosition(ref mySheet, "A1");
Below code worked for me to move horizontal scrollbar to required position.
Used apache poi libraries(poi, poi-ooxml).
((XSSFSheet)sheet).getCTWorksheet().getSheetViews().getSheetViewArray(0).setTopLeftCell("AE11");
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 -
??? ???? ????????? ?? ???????? ??? ?????? ?? ??????
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());
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());
}