Importing null date from Excel - java

I have an excel sheet from where I am reading excel cel values and importing to DB
Using Apache POI :
if (row.getCell(8) != null) {
setActualDeparture(DateUtil.getJavaDate(row.getCell(8).getNumericCellValue()));
}
The excel sheet has null on Cell 8 , so it should not import anything . but it takes dates like 1899-12-31T00:00:00
What could be the issue ?

The Row.getCell(int cellnum) returns only NULL if there is nothing stored in the file for this cell. It returns the cell if there is something stored in the file for this cell. Even if this is only a NumberFormat for example or any other information for this cell.
But there is a second method Row.getCell(int cellnum, Row.MissingCellPolicy policy) http://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/Row.html#getCell%28int,%20org.apache.poi.ss.usermodel.Row.MissingCellPolicy%29 which can be used in your case.
Example:
There is nothing in A1 but there is a special NumberFormat and not General applied.
import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.*;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.InputStream;
class GetEmtyCellTest {
public static void main(String[] args) {
try {
InputStream inp = new FileInputStream("workbook.xlsx");
Workbook wb = WorkbookFactory.create(inp);
Sheet sheet = wb.getSheetAt(0);
Row row = sheet.getRow(0);
System.out.println(row.getCell(0).getNumericCellValue()); //0.0
System.out.println(row.getCell(0, Row.RETURN_BLANK_AS_NULL)); //null
FileOutputStream fileOut = new FileOutputStream("workbook.xlsx");
wb.write(fileOut);
fileOut.flush();
fileOut.close();
} catch (InvalidFormatException ifex) {
} catch (FileNotFoundException fnfex) {
} catch (IOException ioex) {
}
}
}

Related

Read excel data in page object model

Using windows-7 and keep getting errors to write code to ready excel
Trying to read excel data file in java maven Keep getting error on
line#49 sheet= book.getSheet(sheetname); I have added all dependencies and imported but still can not clear this error.
package com.newTour.qa.util;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.apache.poi.hslf.model.Sheet;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import com.newTour.qa.Base.TestBase;
public class TestUtil extends TestBase {
public static String TESTDATA_SHEET_PATH = "C:\\Users\\shahgee\\newtour.qu\\src\\main\\java\\"
+ "com\\qa\\newtour\\testdata\\MercutyTourTestData.xlsx" ;
static Workbook book;
static Sheet sheet;
public static Object[][]getTestData(String sheetname){
FileInputStream file = null;
try {
file = new FileInputStream(TESTDATA_SHEET_PATH);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
book= WorkbookFactory.create(file);
} catch (InvalidFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
sheet = book.getSheet(sheetname);
Object[][]data = new Object[sheet.getLastRowNum()][sheet.getRow(0).getLastCellNum()];
for (int i =0; i <sheet.getLastRowNum();i++){
for (int k =0;k <sheet.getRow(0).getLastCellNum(); k++){
data[i][k]= sheet.getRow(i+1).getCell(k).toString();
}
}
return data;
}
}
try to change the import of Sheet class with
org.apache.poi.ss.usermodel.Sheet
what you use right now is Sheet for Powerpoint Document.
here the reference of the library you use right now:
https://www.oschina.net/uploads/doc/poi-3.1-FINAL/org/apache/poi/hslf/model/Sheet.html

unable to replace the date in the excel file using java

Requirement
i need to open excel file. Then i need to check for the date(12/31/2014). If this exist in the file then i need replace with 11/28/2014. Actually excel file is containing the date. But in my code is never passing this condition if (df.format(DateUtil.getJavaDate(cell.getNumericCellValue())).equals(df.format(asOfDate))) {.
Here is the code:
package excelAsOfDate;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelAsOfDate {
public static void main(String[] args) {
try {
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
Date asOfDate = df.parse("12/31/2014");
Date newAsOfDate = df.parse("11/28/2014");
System.out.println("date as of" + df.format(asOfDate));
File directory = new File("C://Users//kondeti.venkatarao//Documents//Regresion_sheets//test");
File[] files = directory.listFiles();
for (File file : files) {
if (file.getName().toLowerCase().endsWith(".xlsx")) {
FileInputStream fis = new FileInputStream(file.getAbsoluteFile());
// Create Workbook instance holding reference to .xlsx file
XSSFWorkbook workbook = new XSSFWorkbook(fis);
int i = 1;
while (i < workbook.getNumberOfSheets()) {
// Get first/desired sheet from the workbook
XSSFSheet sheet = workbook.getSheetAt(i);
// Iterate through each rows one by one
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
// For each row, iterate through all the columns
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
// Check the cell type and format accordingly
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
if (df.format(DateUtil.getJavaDate(cell.getNumericCellValue())).equals(df.format(asOfDate))) {
// System.out.println(df.format(cell.getDateCellValue()));
System.out.println(df.format(DateUtil.getJavaDate(cell.getNumericCellValue())));
CreationHelper createHelper = workbook.getCreationHelper();
CellStyle cellStyle = workbook.createCellStyle();
cellStyle.setFillForegroundColor(IndexedColors.RED.getIndex());
cellStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
cellStyle.setDataFormat(createHelper.createDataFormat().getFormat("m/d/yy"));
cell.setCellValue(newAsOfDate);
cell.setCellStyle(cellStyle);
}
}
break;
}
}
}
i++;
fis.close();
}
//FileOutputStream fileOut = new FileOutputStream("C://Users//kondeti.venkatarao//Documents//Regresion_sheets//test//final//"+file.getName());
FileOutputStream fileOut = new FileOutputStream(file.getAbsoluteFile());
workbook.write(fileOut);
fileOut.close();
fis.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Logging is a key to find your answers.
As I look into the Cell class, I see there is a method named :
getDateCellCalue()
When we look at the setter of that :
void setCellValue(java.util.Date value)
Converts the supplied date to its equivalent Excel numeric value and sets that into the cell.
So you are not comparing correct.
Mine quick suggestion is :
if (df.format(cell.getDateCellValue()).equals(df.format(asOfDate)))
If this doesn't work, put logging on what the df.format(cell.getDateCellValue() produces as String.
Edit :
Did you also noticed this :
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
Date asOfDate = df.parse("12/31/2014");
Your second date is MM/dd/yyyy

Not able to write output in the excel file using poi in selenium code

I am writing a code to fetch data from an excel sheet and run selenium tests on it and write the output in a different excel file. But I am not able to view the output in the output file. I am getting error as excel found unreadable content in .xlsx message after java code.
package new_excel_package;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
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.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.eclipse.debug.core.model.MemoryByte;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class PoiReadExcelFile {
public static void main(String[] args) {
try {
WebDriver driver = new FirefoxDriver();
FileInputStream fileInputStream = new FileInputStream("D://new.xlsx");
XSSFWorkbook workbook = new XSSFWorkbook(fileInputStream);
XSSFSheet worksheet = workbook.getSheet("check");
FileOutputStream fileOut = new FileOutputStream("D://test.xlsx",true);
XSSFWorkbook workbook_out = new XSSFWorkbook();
XSSFSheet worksheet_out = workbook_out.createSheet("Worksheet");
MemoryByte ms = new MemoryByte();
for(int i = 0; i < worksheet.getLastRowNum()+1;i++)
{
XSSFRow row = worksheet.getRow(i);
//System.out.println(row.toString());
int r = worksheet_out.getLastRowNum();
XSSFRow row1 = worksheet_out.createRow(r+1);
XSSFCell cell_user = row.getCell(0);
String user_names = cell_user.getStringCellValue();
CharSequence[] user_name = {cell_user.getStringCellValue()};
System.out.println("fetched username");
XSSFCell cell_mail = row.getCell(1);
String e_mails = cell_mail.getStringCellValue();
CharSequence[] e_mail = {cell_mail.getStringCellValue()};
System.out.println("fetched email");
driver.get("file:///D:/SANDEEP/html%20sample.html");
driver.findElement(By.name("Name")).sendKeys(user_name);
driver.findElement(By.name("Email")).sendKeys(e_mail);
driver.findElement(By.name("Submit")).click();
//String status = "done";
System.out.println("authenticated for" + user_names);
/*XSSFCell cell_user_out = row1.createCell(0);
cell_user_out.setCellValue(user_names.toString());
XSSFCell cell_mail_out = row1.createCell(1);
cell_user_out.setCellValue(e_mails.toString());
XSSFCell cell_stat_out = row1.createCell(2);
cell_user_out.setCellValue("done");*/
row1.createCell(0,i).setCellValue(user_names.toString());
row1.createCell(1,i).setCellValue(e_mails.toString());
row1.createCell(2,i).setCellValue("done");
System.out.println("user updated");
/*workbook_out.write(fileOut);
System.out.println("elements updated2");*/
}
//workbook.Save("D://test.xlsx",FileFormatType.Excel2007Xlsx);
workbook.write(fileOut);
fileOut.flush();
fileOut.close();
driver.close();
System.out.println("elements updated");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I am also reading the inputs from an excel document and writing the output in a separate excel(.xls) document. Unlike you, I have used HSSFWorkbook which only allows my output to be written in .xls but that should not impact the implementation.
The notable difference I can see is you are writing the workbook before closing the file as shown below:
workbook.write(fileOut);
fileOut.flush();
fileOut.close();
This is how I implemented it:
HSSFWorkbook workbook = new HSSFWorkbook();
String fileName = "excelDoc\\" +(new SimpleDateFormat("dd-MM-yy--hh-mm-ss").format(Calendar.getInstance().getTime()))+ ".xls"; //relative location of file + Time stamp based file name (.xls)
System.out.println(fileName);
FileOutputStream file1 = new FileOutputStream (new File(fileName));
HSSFSheet spreadSheet = workbook.createSheet("Result Document");
HSSFRow row = spreadSheet.createRow((short) 0);
HSSFCell cell;
//Creating rows and filling them with data
cell = row.createCell(0);
cell.setCellValue(new HSSFRichTextString("Test No"));
cell = row.createCell(1);
cell.setCellValue(new HSSFRichTextString("Test Result"));
//Please see below and compare
file1.close(); //Closing the file
FileOutputStream outFile =new FileOutputStream(new File(fileName)); //Creating new file
workbook.write(outFile); //printing the data in the new file
outFile.close(); //closing the new file
System.out.println("The Result are now printed in the excel sheet");
You're missing out this,
XSSFWorkbook workbook_out = new XSSFWorkbook(fileOut);

The PoiReadExcelFile class will read in the 'poi-test.xls' file into an HSSFWorkbook object

I've created this code and The PoiReadExcelFile class will read in the 'poi-test.xls' file into an HSSFWorkbook object. The 'POI Worksheet' will then be read into an HSSFWorksheet object, and then the values within the A1, B1, C1, and D1 cells will be read and displayed to standard output.
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Date;
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;
public class PoiReadExcelFile {
public static void main(String[] args) {
try {
FileInputStream fileInputStream = new FileInputStream("poi-
test.xls");
HSSFWorkbook workbook = new HSSFWorkbook(fileInputStream);
HSSFSheet worksheet = workbook.getSheet("POI Worksheet");
HSSFRow row1 = worksheet.getRow(0);
HSSFCell cellA1 = row1.getCell((short) 0);
String a1Val = cellA1.getStringCellValue();
HSSFCell cellB1 = row1.getCell((short) 1);
String b1Val = cellB1.getStringCellValue();
HSSFCell cellC1 = row1.getCell((short) 2);
boolean c1Val = cellC1.getBooleanCellValue();
HSSFCell cellD1 = row1.getCell((short) 3);
Date d1Val = cellD1.getDateCellValue();
System.out.println("A1: " + a1Val);
System.out.println("B1: " + b1Val);
System.out.println("C1: " + c1Val);
System.out.println("D1: " + d1Val);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
When i ran this code i got this:
Usage: BiffDrawingToXml [options] inputWorkbook
Options:
-exclude-workbook exclude workbook-level records
-sheet-indexes output sheets with specified indexes
-sheet-namek output sheets with specified name
What's the problem?
Please run the class file using right click run option. The above message while come when the only JAR file is getting run.

Writing to .xlsx using java. BiffViewer error occurs

jars I have used : dom4j poi-3.8.jar poi-ooxml-3.8.jar poi-ooxml-schemas-3.8.jar xbean.jar
The code :
package org.capgemini.ui;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Vector;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class XSSFWorkBookWriter {
public void writeWorkBook(Vector table) throws Exception {
XSSFWorkbook workBook = new XSSFWorkbook();
XSSFSheet sheet = workBook.createSheet();
table=new Vector();
table.add(new String("Howdy"));
table.add(new java.sql.Date(2012,06,20));
table.add(new Double(13.35D));
table.add(new String("Fine"));
table.add(new java.sql.Date(2012,06,20));
table.add(new Double(13.38D));
Iterator rows=table.iterator();
Enumeration rowsOfVector=table.elements();
int totalNoOfRows=table.size()/2;
int currentRow=0;
while (rows.hasNext () && currentRow<totalNoOfRows){
XSSFRow row = sheet.createRow(currentRow++);
for (int i = 0; i < 3; i++) {
XSSFCell cell=row.createCell(i);
Object val=rows.next();
if( val instanceof String){
cell.setCellValue(val.toString());
}
else if(val instanceof Date){
cell.setCellValue((java.sql.Date)val);
}
else if(val instanceof Double){
cell.setCellValue((Double)val);
}
}
}
FileOutputStream outPutStream = null;
try {
outPutStream = new FileOutputStream("D:/Try.xlsx");
workBook.write(outPutStream);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (outPutStream != null) {
try {
outPutStream.flush();
outPutStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
XSSFWorkBookWriter bookWriter=new XSSFWorkBookWriter();
try {
bookWriter.writeWorkBook(new Vector());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
ERROR ::
org.apache.poi.hssf.dev.BiffViewer$CommandParseException: Biff viewer needs a filename
at org.apache.poi.hssf.dev.BiffViewer$CommandArgs.parse(BiffViewer.java:333)
at org.apache.poi.hssf.dev.BiffViewer.main(BiffViewer.java:386)
BiffViewer is part of HSSF, which only works with the older .xls files (OLE2 based). You're generating a .xlsx file with XSSF, which is a different low level format.
If you really want to use BiffViewer (not sure why, it's normally only used with debugging, but still), then you'll need to change your XSSF code to be HSSF code. Otherwise, if you did mean to be using XSSF to generate a .xlsx file, then you can't use the HSSF debugging tools. If you want to know what's in your .xlsx file, unzip it (.xlsx is a zip of xml files) and view the XML.

Categories