Null Pointer Exception importing Web elements to Excel [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I'm stuck on a Null Pointer Exception problem. The tests are run through JUnit, but I didn't manage to debug properly and find out the reason of it.
Test class
ExcelActions excelActions;
Excel_Import excel_import;
#Test
public void addResultsToExcel() throws InterruptedException {
searchAfterLogin(); // works fine until the next method
excelActions.addToExcel(); //thats where NPE begins...
excel_import.importExcel(excelActions.addToExcel());
}
Excel Action (Webdriver part)
public class ExcelActions extends BaseAction {
public ExcelActions(WebDriver driver) { super(driver); }
public Map<String, Object[]> addToExcel(){
String beforeXpath_pageName = "//*[#id=\"mw-content-
text\"]/div[3]/ul/li[";
String afterXpath_pageName = "]/div[1]/a";
int rowCount ;
rowCount = 20;
Map<String, Object[]> data = new TreeMap<String, Object[]>();
for(int i = 1; i <= rowCount; i++){
String actualXpath_pageName = beforeXpath_pageName + i +
afterXpath_pageName;
String pageName =
driver.findElement(By.xpath(actualXpath_pageName)).getText();
System.out.println(pageName);
data.put("" + i, new Object[]{pageName});
}
return data;
}
}
Excel import class
public class Excel_Import extends BaseAction {
public Excel_Import(WebDriver driver) { super(driver); }
public void importExcel(Map<String, Object[]> data) {
XSSFWorkbook workbook = new XSSFWorkbook();
//Create a blank sheet
XSSFSheet sheet = workbook.createSheet("Data");
//Iterate over data and write to sheet
Set<String> keyset = data.keySet();
int rownum = 0;
for (String key : keyset)
{
//create a row of excel sheet
Row row = sheet.createRow(rownum++);
//get object array of particular key
Object[] objArr = data.get(key);
int cellnum = 0;
for (Object obj : objArr)
{
Cell cell = row.createCell(cellnum++);
if (obj instanceof String)
{
cell.setCellValue((String) obj);
}
else if (obj instanceof Integer)
{
cell.setCellValue((Integer) obj);
}
}
}
try
{
//Write the workbook in file system
FileOutputStream out = new FileOutputStream(new
File("D:\\Projects\\Cucumber\\src\\main\\resources\\ImportedResults.xlsx"));
workbook.write(out);
out.close();
System.out.println("howtodoinjava_demo.xlsx written successfully on
disk.");
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Could you guys have a look at it?

The field:
ExcelActions excelActions;
is not initialized. You should assign an instance of ExcelActions to it, e.g.:
ExcelActions excelActions = new ExcelActions(someWebDriverMock);
It is not enough to declare a field in a class. You need some specific object to be assigned to it, otherwise it will be null.

Related

How can I stop the output excel file from getting corrupted?

I'm creating a report from the following code and scheduling it using quartz scheduler but when it is saved, it is getting corrupted..
public class GenerateReport implements Job{
XSSFWorkbook report = new XSSFWorkbook();
MyData myData = new MyData();
public XSSFWorkbook createReport() {
Map<Integer, String> data = new HashMap<Integer, String>();
myData.setData(1652, "Abcs");
myData.setData(1682, "ksaos");
myData.setData(1152, "oass");
myData.setData(1962, "Aajas");
data = myData.getData();
XSSFSheet sheet = report.createSheet("Employee data");
XSSFCellStyle headerStyle = report.createCellStyle();
XSSFFont headerFont = report.createFont();
headerFont.setBold(true);
headerStyle.setFont(headerFont);
XSSFCell cell = null;
XSSFRow row;
int rowNum = 0;
int colNum = 0;
row = sheet.createRow(rowNum++);
row.createCell(colNum++).setCellValue("ID");
row.createCell(colNum).setCellValue("Name");
for(Map.Entry<Integer, String> entry: data.entrySet()) {
colNum = 0;
row = sheet.createRow(rowNum++);
cell = row.createCell(colNum++);
cell.setCellValue(entry.getKey());
cell = row.createCell(colNum);
cell.setCellValue(entry.getValue());
}
return report;
}
public void saveReport() {
XSSFWorkbook finalWorkbook = new XSSFWorkbook();
try {
FileOutputStream fos = new FileOutputStream("C:\\Users\\ra185586\\Desktop\\written.xlsx");
finalWorkbook.write(fos);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.print("Report generated");
}
#Override
public void execute(JobExecutionContext arg0) throws JobExecutionException {
createReport();
saveReport();
System.out.println(" and saved");
}
}
Can you guys help me to resolve, so that when the report is saved, it does not gets corrupt.
Thank you!
You method createReport() return XSSFWorkbook. And you need transfer this XSSFWorkbook to saveReport.
-Change in execute two line on saveReport(createReport());
-Delete line in saveReport XSSFWorkbook finalWorkbook = new XSSFWorkbook();
-Add arguments in saveReport saveReport(XSSFWorkbook finalWorkbook)

Repair error pop up in .xlsx file in mail in zip format in java apache poi

I have used apache poi 3.11 to generate .xlsx files. After that we were required to zip it and send it via email.
But then we try to open the file within the email we get the
"We found a problem with some content in 'FileName.xlsx'.Do you want
us to try to recover as much as we can? If you trust the source of
this workbook, Click Yes"
popup. and recovers our data as well. But i do not understand why this error occurs.
We have even tried to generate this code using fileOutputStream "Temp.xlsx" this time there is no error popup. But when we write the workbook to a byteoutputstream . It gives us this error. We have even set the mimeType as "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
We have attached the code snippet plus the popup image.
Please guide us further!
For reference below is the code:
#Override
public ByteArrayOutputStream createWorkBookForEmailXSSF(ExtractionRequestBean extractionRequestBeans, ByteArrayOutputStream outputstream) throws FileNotFoundException, IOException {
XSSFWorkbook xwb = new XSSFWorkbook();
XSSFCellStyle headerStyle= SpreadSheetGenerator.settingHeaderStyle(xwb);
SpreadSheetGenerator.setttingNumberStyle(xwb);
SpreadSheetGenerator.setttingNumberDecimalStyle(xwb);
SpreadSheetGenerator.setttingDateStyle(xwb);
XSSFSheet sheet = xwb.createSheet(extractionRequestBeans.getFileName());
SpreadSheetGenerator.createHeader(sheet, extractionRequestBeans.getHeaderValues(), headerStyle);
SpreadSheetGenerator.createRows(extractionRequestBeans, sheet, xwb);
SpreadSheetGenerator.settingAutosizeColumns(sheet, extractionRequestBeans.getHeaderValues());
xwb.write(outputstream);
outputstream.write(xwb.toString().getBytes());
outputstream.close();
return outputstream;
}
}
public static XSSFCellStyle settingHeaderStyle(XSSFWorkbook xwb) {
XSSFCellStyle style = xwb.createCellStyle();
XSSFFont font = xwb.createFont();
//font.setBoldweight(Font.BOLDWEIGHT_BOLD);
style.setFillForegroundColor(IndexedColors.GREY_40_PERCENT.getIndex());
//style.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);
style.setFont(font);
return style;
}
public static XSSFCellStyle setttingNumberStyle(XSSFWorkbook xwb) {
XSSFCellStyle style = xwb.createCellStyle();
DataFormat format = xwb.createDataFormat();
style.setDataFormat(format.getFormat("0"));
return style;
}
public static XSSFCellStyle setttingNumberDecimalStyle(XSSFWorkbook xwb) {
XSSFCellStyle style = xwb.createCellStyle();
DataFormat format = xwb.createDataFormat();
style.setDataFormat(format.getFormat("0.00"));
return style;
}
public static XSSFCellStyle setttingDateStyle(XSSFWorkbook xwb) {
XSSFCellStyle style = xwb.createCellStyle();
DataFormat format = xwb.createDataFormat();
style.setDataFormat(format.getFormat("m/d/yy h:mm"));
return style;
}
public static void createHeader(XSSFSheet sheet, List<String> headerValues, XSSFCellStyle style) {
addHeaderRow(sheet, 0, headerValues, style);
}
private static void addHeaderRow(XSSFSheet sheet, int i, List<String> headerValues, XSSFCellStyle style) {
logger.info("Start : [SpreadSheetGenerator - createHeaderRow - Start Generating Header]");
XSSFRow rowhead = sheet.createRow((int) 0);
int cellIndex = 0;
for (String headerLabel : headerValues) {
addHeaderCell(rowhead, cellIndex, headerLabel, style);
cellIndex++;
}
logger.info("End : [SpreadSheetGenerator - createHeaderRow - Start Generating Header]");
}
private static void addHeaderCell(XSSFRow rowhead, int cellIndex, String headerLabel, XSSFCellStyle style) {
if (headerLabel != null && !headerLabel.equalsIgnoreCase("")) {
rowhead.createCell(cellIndex).setCellValue(headerLabel.toString());
} else {
rowhead.createCell(cellIndex).setCellValue("");
}
rowhead.getCell(cellIndex).setCellStyle(style);
}
public static void settingAutosizeColumns(XSSFSheet sheet, List<String> headerValues) {
for (int autoSizeIndex = 0; autoSizeIndex < headerValues.size(); autoSizeIndex++) {
sheet.autoSizeColumn(autoSizeIndex);
}
}
public static void createRows(ExtractionRequestBean extractionRequestBean, XSSFSheet sheet, XSSFWorkbook hwb) {
logger.info("Start : [SpreadSheetGenerator - createRows - Start Generating Excel Rows ]");
int rowIndex = 1;
for (Object[] obj : extractionRequestBean.getDatas()) {
addRow(sheet, rowIndex, obj, extractionRequestBean.getCellStyleMap(), hwb);
rowIndex++;
}
logger.info("End : [SpreadSheetGenerator - createRows - End Generating Excel Rows]");
}
private static void addRow(XSSFSheet sheet, int rowIndex, Object[] obj, Map<Integer, Integer> cellStyleMap, XSSFWorkbook hwb) {
XSSFRow row = sheet.createRow((int) rowIndex);
int cellIndex = 0;
addCell(obj, row, cellIndex, cellStyleMap, hwb);
}
#SuppressWarnings("deprecation")
private static void addCell(Object[] obj, XSSFRow row, int cellIndex, Map<Integer, Integer> cellStyleMap, XSSFWorkbook hwb) {
for (Object object : obj) {
if (cellStyleMap.get(cellIndex) == HSSFCellStyleEnum.ONLYSTRING.getStyleCode()) {
row.createCell(cellIndex).setCellValue(object != null ? object.toString() : "");
} else if (cellStyleMap.get(cellIndex) == HSSFCellStyleEnum.NUMERICWITHDECIMAL.getStyleCode()) {
row.createCell(cellIndex).setCellValue(object != null ? Double.valueOf(object.toString()) : 0d);
} else if (cellStyleMap.get(cellIndex) == HSSFCellStyleEnum.NUMERICWITHOUTDECIMAL.getStyleCode()) {
row.createCell(cellIndex).setCellValue(object != null ? Double.valueOf(object.toString()) : 0d);
} else if (cellStyleMap.get(cellIndex) == HSSFCellStyleEnum.ONLYDATE.getStyleCode()) {
row.createCell(cellIndex).setCellValue(object != null ? DateUtil.formatDateOnly(new Date(object.toString())) : "");
}
cellIndex++;
}
}

Pulling data from multiple Excel sheets with #Dataprovider and passing it to #test

I am facing an issue related to #Dataprovider and #Test
Scenario : I need to get data from multiple sheets(sheet1, sheet2, sheet3, .....) with help of #dataprovider annotation, I have web application in which there are multiple webpages in which I have to pass data.
I've implemented it using POM, I need to get the data from multiple sheets at once and pass it to #test.
below is the snippet:
#DataProvider
public Object[][] getHrwsIdentityData() throws IOException
{
List<Object[]> DataList = null;
loggerManager.logger.info("Reading the position testdata from excel sheet");
DataList = Excel.excelRead(".\\resources\\data\\HR Workwise Automation -New Hires.xlsx", "Identity Details", "Execute Flag", "Y");
return DataList.toArray(new Object[DataList.size()][]);
}
#DataProvider
public Object[][] getHrwsPersonalData() throws IOException
{
List<Object[]> DataList = null;
loggerManager.logger.info("Reading the position testdata from excel sheet");
DataList = Excel.excelRead(".\\resources\\data\\HR Workwise Automation -New Hires.xlsx", "Personal Information", "Execute Flag", "Y");
return DataList.toArray(new Object[DataList.size()][]);
}
#Test(priority = 1,enabled = true, dataProvider="getHrwsPersonalData", description="Add New Employee in Manage Employees Page; Coverage: AddNewEmployee")
public void updateEmployeePersonalInfo(LinkedHashMap<String, String> DataSet) throws IOException
{
hrws.addEmployeePersonalInfo(DataSet);
}
#Test(priority = 2,enabled = true, dataProvider="getHrwsJobInformation", description="Add New Employee in Manage Employees Page; Coverage: AddNewEmployee")
public void updateEmployeeJobInfo(LinkedHashMap<String, String> DataSet) throws IOException
{
hrws.addEmployeeJobInfo(DataSet);
}
I tried using different single #DataProviders for each #Test, but No Luck!!
Also below is the readExcel file
public static List<Object[]> excelRead(String sExcelPath, String sSheetName, String sCondCol, String sCondVal) throws IOException{
String[] sHeaderKey = new String[0];
String[] sValue = new String[0];
LinkedHashMap<String, String> RowData;
List<Object[]> DataList = new ArrayList<>();
try {
FileInputStream oFis = new FileInputStream(sExcelPath);
Workbook workbook = null;
// Using XSSF for xlsx format, for xls use HSSF
workbook = new XSSFWorkbook(oFis);
Sheet sheet = workbook.getSheet(sSheetName);
Iterator<Row> rowIterator = sheet.iterator();
DataFormatter formatter = new DataFormatter(Locale.US);
while (rowIterator.hasNext()) {
Boolean bHeaderRow = false;
sValue = new String[0];
Row row = rowIterator.next();
if (row.getRowNum() == 0) {
bHeaderRow = true;
}
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
if (bHeaderRow && (cell.getCellType() != Cell.CELL_TYPE_BLANK)) {
sHeaderKey = Arrays.copyOf(sHeaderKey, sHeaderKey.length + 1);
sHeaderKey[cell.getColumnIndex()] = formatter.formatCellValue(cell);
} else if ((!bHeaderRow) && (sHeaderKey[cell.getColumnIndex()] != null)) {
sValue = Arrays.copyOf(sValue, sValue.length + 1);
sValue[cell.getColumnIndex()] = formatter.formatCellValue(cell);
}
}
if ((sHeaderKey.length != 0) && (sValue.length != 0)) {
RowData = new LinkedHashMap<String, String>();
for (int i = 0; i < sHeaderKey.length; i++) {
RowData.put(sHeaderKey[i], sValue[i]);
}
if(RowData.get(sCondCol).trim().toLowerCase().equals(sCondVal.trim().toLowerCase())){
DataList.add(new Object[]{RowData});
}
}
}
workbook.close();
oFis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw e;
}
return DataList;
}
I need to merge these two #dataproviders into one!!
You dont need to have multiple data provider for different tests. You need a mechanism to identify which test is calling the data provider. TestNg data providers are overloaded, you can create a data provider method like this Please don't be critical to the code inside this method as its just for demonstration
#DataProvider(name = "AllTestData")
public static Object[][] GetDataForEveryOne(ITestNGMethod testContext)
{
if(testContext.getMethodName().equals("LoginWithMultipleUsersTest"))
{
String[][] usernamePassArray = { { "testType1", "pass1" },
{ "testType2", "pass1" }};
return usernamePassArray;
}
else if(testContext.getMethodName().equals("LoginWithMultipleDataTest"))
{
String[][] usernamePassArray = { { "user1", "pass1" },
{ "user2", "pass2" },
{ "user3", "pass3" } };
return usernamePassArray;
}
return null;
}
I have just trying to show how you can get the Test context in data provider which in turn can let you get the test method name. This test method name can be used as a key to extract data from Excel corresponding to this test.

How to write excel using Apache POI with TestNG dataProvider

I am working with hybrid framework, in these for writing an excel sheet I am using Apache-poi library by data provider.
I want my code in these way that by using it I can read and write my excel sheet in which test cases has been written and according to that cases it set their status.
Currently when I am executing my code it skipped the login method. Actually I am beginner in it and try to using it for read and write the excel, can anyone please help me to resolved the problem?
public class HybridExecuteTest {
private static final String BROWSER_PATH = "D:\\abc\\setup\\FFinstalled\\firefox.exe";
private static XSSFWorkbook ExcelWBook;
private static XSSFSheet ExcelWSheet;
private static XSSFCell Cell;
private static XSSFRow Row;
WebDriver webdriver = null;
#Test(dataProvider = "hybridData")
public void testLogin(String testcaseName, String keyword,
String objectName, String objectType, String value)
throws Exception {
// TODO Auto-generated method stub
if (testcaseName != null && testcaseName.length() != 0) {
// webdriver=new FirefoxDriver();
File file = new File(BROWSER_PATH);
FirefoxBinary fb = new FirefoxBinary(file);
webdriver = new FirefoxDriver(fb, new FirefoxProfile());
}
ReadObject object = new ReadObject();
Properties allObjects = object.getObjectRepository();
UIOperation operation = new UIOperation(webdriver);
// Call perform function to perform operation on UI
operation.perform(allObjects, keyword, objectName, objectType, value);
}
#DataProvider(name = "hybridData")
// This method is to set the File path and to open the Excel file, Pass Excel Path and Sheetname as Arguments to this method
public Object[][] setExcelFile(String filePath, String fileName, String sheetName) throws Exception {
Object object[][] = null;
try {
File file = new File(filePath + "\\" + fileName);
// Open the Excel file
FileInputStream ExcelFile = new FileInputStream(file);
// Access the required test data sheet
ExcelWBook = new XSSFWorkbook(ExcelFile);
ExcelWSheet = ExcelWBook.getSheet(sheetName);
} catch (Exception e) {throw (e);}
return object;
}
// This method is to read the test data from the Excel cell, in this we are passing parameters as Row num and Col num
public String getCellData(int RowNum, int ColNum) throws Exception {
try {
Cell = ExcelWSheet.getRow(RowNum).getCell(ColNum);
String CellData = Cell.getStringCellValue();
return CellData;
} catch (Exception e) {
return "";
}
}
// This method is to write in the Excel cell, Row num and Col num are the parameters
public String setCellData(String Result, int RowNum, int ColNum,String filePath, String fileName) throws Exception {
try {
Row = ExcelWSheet.getRow(RowNum);
Cell = Row.getCell(ColNum, Row.RETURN_BLANK_AS_NULL);
if (Cell == null) {
Cell = Row.createCell(ColNum);
Cell.setCellValue(Result);
} else {
Cell.setCellValue(Result);
}
// Constant variables Test Data path and Test Data file name
File file = new File(filePath + "\\" + fileName);
// Open the Excel file
FileOutputStream ExcelFile = new FileOutputStream(file);
ExcelWBook.write(ExcelFile);
} catch (Exception e) {
throw (e);
}
return null;
}
}
Console:
SKIPPED: testLogin
org.testng.TestNGException:
Some DataProvider public java.lang.Object[][] testCases.HybridExecuteTest.setExcelFile(java.lang.String,java.lang.String,java.lang.String) throws java.lang.Exception parameters unresolved: at 1 type class java.lang.String
at 2 type class java.lang.String
at 3 type class java.lang.String
Note: I have go through the tutorial of Apache poi and normally I understand how to write but in framework I am stuck. Please help in these.
You have tried to pass parameters to dataprovider, this is not supported.declare String filePath, String fileName, String sheetName as class level variables and then access them from the method.
String filePath="something"; String fileName="something"; String sheetName ="something";
#DataProvider(name = "hybridData")
public Object[][] setExcelFile() throws Exception {
Object object[][] = null;
try {
File file = new File(filePath + "\\" + fileName);
// Open the Excel file
FileInputStream ExcelFile = new FileInputStream(file);
// Access the required test data sheet
ExcelWBook = new XSSFWorkbook(ExcelFile);
ExcelWSheet = ExcelWBook.getSheet(sheetName);
} catch (Exception e) {throw (e);}
return object;
}
Another problem that you will face is that you are not assigning anything to object[][] before returning it.

how to get data from excel file?

Actually i am working on a java program that extracts data from an Excel file,
and i am using the POI Library, as a matter of fact i must specify the type of every extracted value, but the file contains a huge number of data with different types,
So i am asking if there is another way to get all the data as a string.
Thank you.
Best regards
package DAO;
import java.io.FileInputStream;
import java.util.Iterator;
import java.util.Vector;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
public class ReadExcelFile {
public static void main(String[] args) {
String fileName = "C:\\Users\\marrah\\Desktop\\TRIAL FILE1.xls";
Vector dataHolder = ReadCSV(fileName);
printCellData(dataHolder);
}
public static Vector ReadCSV(String fileName) {
Vector cellVectorHolder = new Vector();
try {
FileInputStream myInput = new FileInputStream(fileName);
POIFSFileSystem myFileSystem = new POIFSFileSystem(myInput);
HSSFWorkbook myWorkBook = new HSSFWorkbook(myFileSystem);
HSSFSheet mySheet = myWorkBook.getSheetAt(0);
Iterator rowIter = mySheet.rowIterator();
while (rowIter.hasNext()) {
HSSFRow myRow = (HSSFRow) rowIter.next();
Iterator cellIter = myRow.cellIterator();
Vector cellStoreVector = new Vector();
while (cellIter.hasNext()) {
HSSFCell myCell = (HSSFCell) cellIter.next();
cellStoreVector.addElement(myCell);
}
cellVectorHolder.addElement(cellStoreVector);
}
} catch (Exception e) {
e.printStackTrace();
}
return cellVectorHolder;
}
private static void printCellData(Vector dataHolder) {
for (int i = 0; i < dataHolder.size(); i++) {
Vector cellStoreVector = (Vector) dataHolder.elementAt(i);
for (int j = 0; j < cellStoreVector.size(); j++) {
HSSFCell myCell = (HSSFCell) cellStoreVector.elementAt(j);
Object stringCellValue="";
stringCellValue =cellStoreVector.get(j).toString();
System.out.print(stringCellValue.toString()+"\t");
}
}
}
}
I have a unit-test where I use the following to extract all text from an Excel file without any of the formatting, for some use-cases this might be quicker than iterating over all the elements one-by-one:
private POITextExtractor extractText(File file) throws IOException {
InputStream inp = null;
try {
inp = new PushbackInputStream(
new FileInputStream(file), 8);
if(POIFSFileSystem.hasPOIFSHeader(inp)) {
return createExtractor(new POIFSFileSystem(inp));
}
throw new IllegalArgumentException("Your File was neither an OLE2 file, nor an OOXML file");
} finally {
if(inp != null) inp.close();
}
}
private static POITextExtractor createExtractor(POIFSFileSystem fs) throws IOException {
return createExtractor(fs.getRoot(), fs);
}
private static POITextExtractor createExtractor(DirectoryNode poifsDir, POIFSFileSystem fs) throws IOException {
for(Iterator<Entry> entries = poifsDir.getEntries(); entries.hasNext(); ) {
Entry entry = entries.next();
if(entry.getName().equals("Workbook")) {
{
return new ExcelExtractor(poifsDir, fs);
}
}
}
throw new IllegalArgumentException("No supported documents found in the OLE2 stream");
}
private String assertContains(File file, String... contents) throws IOException {
assertTrue(file.exists());
POITextExtractor extractor = extractText(file);
assertNotNull(extractor);
String str = extractor.getText();
for(String s : contents) {
assertTrue("Did expect to find text '" + s + "' in resulting Excel file, but did not find it in str: " + str, str.contains(s));
}
return str;
}
You can create a common function to use on every cell when you runs thru each row, which validates the data type and then retrieves it in your preferred format. So you move row to row and, for each cell you call something like:
private static String getCellvalue(HSSFRow poiRow, int intColActual) {
if (poiFilaActual != null && poiRowActual.getLastCellNum() >= (short) intColActual) {
HSSFCell cell = poiRowActual.getCell(intColActual);
if (cell != null) {
if (HSSFCell.CELL_TYPE_STRING == cell.getCellType()) {
return cell.getRichStringCellValue().toString();
} else if (HSSFCell.CELL_TYPE_BOOLEAN == cell.getCellType()) {
return new String( (cell.getBooleanCellValue() == true ? "true" : "false") );
} else if (HSSFCell.CELL_TYPE_BLANK == cell.getCellType()) {
return "";
} else if (HSSFCell.CELL_TYPE_NUMERIC == cell.getCellType()) {
if(HSSFDateUtil.isCellDateFormatted(cell)){
return ( new SimpleDateFormat("dd/MM/yyyy").format(cell.getDateCellValue()) );
}else{
return new BigDecimal(cell.getNumericCellValue()).toString();
}
}
}
}
return null;
}

Categories

Resources