how to write .xlsx file using apache poi - apache-poi

please see this is my coding about to write .xlsx file it is working but i can't open file after wrote. it says file is corrupted. please give solution
OPCPackage fileSystems = OPCPackage.open(file.getAbsolutePath(),PackageAccess.READ);
XSSFWorkbook workBook = new XSSFWorkbook(fileSystems);
XSSFSheet sheet = workBook.getSheetAt(0);
Iterator rows = sheet.rowIterator();
while (rows.hasNext ())
{
XSSFRow row = (XSSFRow) rows.next ();
System.out.println ("Row No.: " + row.getRowNum ());
Iterator cells = row.cellIterator();
while (cells.hasNext ())
{
XSSFCell cell = (XSSFCell) cells.next();
String value = "OldValue";
if(value.equals(cell.getStringCellValue()))
{
switch (cell.getCellType())
{
case Cell.CELL_TYPE_NUMERIC:
double cellNumericValue = cell.getNumericCellValue();
cell.setCellValue(cellNumericValue);
break;
case Cell.CELL_TYPE_STRING:
String cellStringValue = cell.getStringCellValue();
cell.setCellValue("NewValue");
break;
case Cell.CELL_TYPE_FORMULA:
String cellFormulaValue = cell.getCellFormula();
cell.setCellValue(cellFormulaValue);
break;
case Cell.CELL_TYPE_BLANK:
cell.setCellValue("");
break;
case Cell.CELL_TYPE_BOOLEAN:
boolean cellBooleanValue = cell.getBooleanCellValue();
cellBooleanValue=false;
cell.setCellValue(cellBooleanValue);
break;
case Cell.CELL_TYPE_ERROR:
byte error = cell.getErrorCellValue();
cell.setCellValue(error);
break;
default:
break;
}
}
}
}
XSSFWorkbook newWorkBook = new XSSFWorkbook();
FileOutputStream outPutStream = null;
try {
outPutStream = new FileOutputStream(file);
newWorkBook.write(outPutStream);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (outPutStream != null) {
try {
outPutStream.flush();
outPutStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

You appear to be creating a workbook, populating it, then creating a new empty one and saving that! Try removing the line
XSSFWorkbook newWorkBook = new XSSFWorkbook();
And then change the write to be a write from workBook rather than newWorkBook and you should be fine.

Related

Invalid header signature; read 0x6D78206C6D74683C, expected 0xE11AB1A1E011CFD0

Invalid header signature; read 0x6D78206C6D74683C, expected 0xE11AB1A1E011CFD0 getting the above error when I am trying to read excel sheet. xls format.
when I try to open the sheet manually I get this error : "The file format and extension of '*******.xls' don't match. The file could be corrupted or unsafe.
String strCompleteFilepath=this.strFilePath + File.separator +
this.strFileName;
int strRowIndex=0;
int strColIndex=0;
String strCompVal="";
try{
InputStream file = new FileInputStream(strCompleteFilepath);
HSSFWorkbook workbook = new HSSFWorkbook(file);
HSSFSheet sheet = workbook.getSheetAt(0);
int strRowCount= sheet.getLastRowNum();
if(strRowCount>0)
{
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext())
{
Row row = (Row)rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext())
{
Cell cell = (Cell)cellIterator.next();
String strCellValue=cell.toString();
if (strCellValue.contentEquals(strKeyIdentifier))
{
strRowIndex=cell.getRowIndex();
System.out.println("The row number where
"+strKeyIdentifier+"is found: "+strRowIndex);
}
if (strCellValue.contentEquals(strColName))
{
strColIndex=cell.getColumnIndex();
System.out.println("The column where "+strColName+" is
found: "+strColIndex);
}
}
}
HSSFCell CompValue=sheet.getRow(strRowIndex).getCell(strColIndex);
switch (CompValue.getCellType())
{
case 0:
if (DateUtil.isCellDateFormatted(CompValue))
{
strCompVal = CompValue.getDateCellValue().toString();
} else
{
strCompVal = String.valueOf(CompValue.getNumericCellValue());
}
break;
case 2:
strCompVal = String.valueOf(CompValue.getBooleanCellValue());
break;
case 1:
strCompVal = CompValue.getStringCellValue();
}
//strCompVal=CompValue.toString();
file.close();
FileOutputStream out = new FileOutputStream(new `
File(strCompleteFilepath));
workbook.write(out);
out.close();
}
else
{
System.out.println("There is no data in the excel, the row count is : "+strRowCount);
}
}
catch (Exception ex)
{
System.out.println(ex.getMessage());
}
return strCompVal;

Apache poi autosizecolumn is not working

i want to write a list of object to an excel file.But autoSizeColumn is not working.My code is below :
List<ReportTmPerHour> reportTm = reportTm();
Iterator<ReportTmPerHour> iterator = reportTm.iterator();
String fileName="C:\\Users\\kkk\\Desktop\\mmm_ccc.xlsx";
Workbook workbook = null;
if(fileName.endsWith("xlsx")){
workbook = new XSSFWorkbook();
}else if(fileName.endsWith("xls")){
workbook = new HSSFWorkbook();
}else{
try {
throw new Exception("invalid file name, should be xls or xlsx");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Sheet sheet = workbook.createSheet("TM");
int rowIndex = 0;
createHeadersForTm(sheet);
while(iterator.hasNext()){
ReportTmPerHour reportTmPerHour = iterator.next();
Row row = sheet.createRow(++rowIndex);
Cell cell = row.createCell(0);
cell.setCellValue(reportTmPerHour.getIsemriNo());
cell.setCellStyle(arg0);
Cell cell10 = row.createCell(1);
cell10.setCellValue(reportTmPerHour.getSube());
Cell cell11=row.createCell(2);
cell11.setCellValue(reportTmPerHour.getAob());
Cell cell12=row.createCell(3);
cell12.setCellValue(reportTmPerHour.getKesintiBildirim());
Cell cell13=row.createCell(4);
cell13.setCellValue(reportTmPerHour.getAciklama());
Cell cell14=row.createCell(5);
cell14.setCellValue(reportTmPerHour.getEtkilenenMahalleler());
Cell cell15=row.createCell(6);
if (reportTmPerHour.getBaslamaZamani()!=null) {
cell15.setCellValue(reportTmPerHour.getBaslamaZamani());
}
Cell cell16=row.createCell(7);
cell16.setCellValue(reportTmPerHour.getTahminiBitisZamani());
Cell cell17=row.createCell(8);
cell17.setCellValue(reportTmPerHour.getTmName());
Cell cell18=row.createCell(9);
cell18.setCellValue(reportTmPerHour.getEtkilenensayi());
}
columnAutoSize(sheet);
//lets write the excel data to file now
FileOutputStream fos;
try {
fos = new FileOutputStream(new File(fileName));
workbook.write(fos);
fos.close();
System.out.println(fileName + " written successfully");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
It does not adjust the columns according to the biggest column size.I use the last version of poiI have seen lots of questions like this.I adjust the size of columns after filling the cells.But this is not working also.Thanx in advance
EDIT
My columnAutoSize(sheet) is below :
private void columnAutoSize(Sheet sheet) {
for(int columnPosition = 1; columnPosition< 9; columnPosition++) {
sheet.autoSizeColumn(columnPosition);
}
}

Selenium excel read and write to find row number

In my program I want to find the row number in the excel sheet matching the string I have passed as argument . It works fine for first and second row but problem is with the next rows. My code to find row number is as below :
public int findrownum(String sName, String value, int cNum) throws Exception{
File excel = new File(filepath);
FileInputStream fis = new FileInputStream(excel);
XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet ws = wb.getSheet(sName);
boolean check = true;
int i=0;
while (check){
XSSFRow rowH = ws.getRow(i);
XSSFCell cell = rowH.getCell(cNum);
String cellvalue = cellToString(cell);
if (cellvalue.equals(value)){
check = false;
}
else {
i = i+1;
}
}
return i;
}
}
I want to read third row that is the string with name registration from the excel
Sl No test case name result timestamp
1 login Pass 03/03/2014 12:11:43 PM
2 Registration
Please let me know what changes needs to be done in the code .
Thanks
I used the similar logic as mentioned by #eric in JUNIT now i am able to find the row number .But now its giving error while i try to read the data using this row number . My code to read data is as below . Please let me know what changes needs to be done public String dataread(String sName, int rNum, String cName) throws Exception{
File excel = new File(filepath);
FileInputStream fis = new FileInputStream(excel);
XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet ws = wb.getSheet(sName);
XSSFRow rowH = ws.getRow(rNum-1);
int totalRows = ws.getLastRowNum();
int i =0;
for(i=0;i<=totalRows;i++)
{
XSSFCell cell = rowH.getCell(i);
String value = cellToString(cell);
if (value.equals(cName)){
System.out.println(i);
break;
}
}
XSSFRow row = ws.getRow(rNum);
XSSFCell cell = row.getCell(i);
String value = cellToString(cell) return value;
}
In general From this Documentation you can use the getHeight() to get in which your cursor instead of writing up your own loop. Obviously this would reduce the execution time as well. Also the code which you have written could have caused the exception,as there is no more physical rows.
ws.getRow(i); can cause a fatal error if i>height of the last row
Hope the following code helps. The assumption is the data in the cell is string data. Also this is with apache poi api.
public static String getcellValue(int testRowNo, int colNo)
{
String projectPath = System.getProperty("user.dir");
String excelPath = projectPath + "/TestSet.xlsx";
File excel = new File(excelPath);
FileInputStream fis = null;
Workbook workBook = null;
String cellValue = null;
try
{
fis = new FileInputStream(excel);
workBook = WorkbookFactory.create(fis);
Sheet workSheet = workBook.getSheet(sheetName);
int totalRows = workSheet.getLastRowNum();
Row row = null;
cellValue = workSheet.getRow(testRowNo).getCell(colNo).getStringCellValue();
} catch (InvalidFormatException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}finally
{
try
{
fis.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
return cellValue;
}
public static int getrowNumber(String sheetName, String cellData)
{
String projectPath = System.getProperty("user.dir");
String excelPath = projectPath + "/TestSet.xlsx";
File excel = new File(excelPath);
FileInputStream fis = null;
Workbook workBook = null;
String cellValue = null;
try
{
fis = new FileInputStream(excel);
workBook = WorkbookFactory.create(fis);
Sheet workSheet = workBook.getSheet(sheetName);
int totalRows = workSheet.getLastRowNum();
Row row = null;
int testRowNo = 0;
for(int rowNo =1; rowNo<=totalRows; rowNo++)
{
row = workSheet.getRow(rowNo);
testRowNo = testRowNo +1;
if(row.getCell(0).getStringCellValue().equalsIgnoreCase(cellData))
{
break;
}
}
} catch (InvalidFormatException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}finally
{
try
{
fis.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
return testRowNo;
}

XSSFSheet get all cell type values as string

Is there any possiblity to get all types(numeric,date,string etc) as String only.I couldn't find such methods.
sheet.getCell(rowIndex,colIndex) like this ?
InputStream ExcelFileToRead = new FileInputStream(file1);
XSSFWorkbook wb = new XSSFWorkbook(ExcelFileToRead);
XSSFWorkbook test = new XSSFWorkbook();
XSSFSheet sheet = wb.getSheetAt(0);
XSSFRow row;
XSSFCell cell;
Iterator rows = sheet.rowIterator();
String[] Excelarray=new String[26];
int count=0;
Map<String, String> data = new HashMap<String, String>();
while (rows.hasNext())
{
row=(XSSFRow) rows.next();
Iterator cells = row.cellIterator();
while (cells.hasNext())
{
cell=(XSSFCell) cells.next();
if (cell.getCellType() == XSSFCell.CELL_TYPE_STRING)
{
System.out.print(cell.getStringCellValue()+",");
}
else if(cell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC)
{
System.out.print(cell.getNumericCellValue()+",");
}
else
{
}
}
System.out.println("----Closed");
}
Someone else already supplied a generic implementation that does what you are looking to do. POI doesn't have anything directly but it's easy enough to make a helper method/class.
Yes, It is possible to get all the values in the form of string.
Previously I had used DataFormatter to get the string value but while working with the large files I found it does not work so well.
Here is the required code: -
for (Row row : sheet) {
DataFormatter dataFormatter = new DataFormatter();
for (Cell cell : row) {
String cellValue = getStringCellValue(cell);
}
}
private static String getStringCellValue(Cell cell) {
try {
switch (cell.getCellType()) {
case FORMULA:
try {
return NumberToTextConverter.toText(cell.getNumericCellValue());
} catch (NumberFormatException e) {
return cell.getStringCellValue();
}
case NUMERIC:
return NumberToTextConverter.toText(cell.getNumericCellValue());
case STRING:
String cellValue = cell.getStringCellValue().trim();
String pattern = "\\^\\$?-?([1-9][0-9]{0,2}(,\\d{3})*(\\.\\d{0,2})?|[1-9]\\d*(\\.\\d{0,2})?|0(\\.\\d{0,2})?|(\\.\\d{1,2}))$|^-?\\$?([1-9]\\d{0,2}(,\\d{3})*(\\.\\d{0,2})?|[1-9]\\d*(\\.\\d{0,2})?|0(\\.\\d{0,2})?|(\\.\\d{1,2}))$|^\\(\\$?([1-9]\\d{0,2}(,\\d{3})*(\\.\\d{0,2})?|[1-9]\\d*(\\.\\d{0,2})?|0(\\.\\d{0,2})?|(\\.\\d{1,2}))\\)$";
if (((Pattern.compile(pattern)).matcher(cellValue)).find()) {
return cellValue.replaceAll("[^\\d.]", "");
}
return cellValue.trim();
case BOOLEAN:
return String.valueOf(cell.getBooleanCellValue());
case ERROR:
return null;
default:
return cell.getStringCellValue();
}
} catch (Exception e) {
if (e.getLocalizedMessage() != null && ConfigReader.isDisplayWarnLog())
return "";
}
return "";
}
It works well. Thank You.

ApachePOI and TestNG

Issues:-
The dataprovider is directly going to exception block
How to return value of cell from data provider to #Test method in order to achieve parameterisation
#DataProvider (name = "DP1")
public void getData() throws IOException {
try
{
FileInputStream file = new FileInputStream(new File("C:\\Users\\kk\\workspace\\K\\TestNG_Tutorial\\src\\Book1.xls"));
System.out.println(file);
//Get the workbook instance for XLS file
HSSFWorkbook workbook = new HSSFWorkbook(file);
//Get first sheet from the workbook
HSSFSheet sheet = workbook.getSheetAt(0);
//Get iterator to all the rows in current sheet
java.util.Iterator<Row> rowIterator = sheet.iterator();
while(rowIterator.hasNext()) {
Row row = rowIterator.next();
//System.out.println("Row is" +row);
java.util.Iterator<Cell> cellIterator = row.cellIterator();
while(cellIterator.hasNext()){
Cell cell = cellIterator.next();
switch(cell.getCellType()) {
case Cell.CELL_TYPE_BOOLEAN:
System.out.print(cell.getBooleanCellValue() + "\t\t");
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t\t");
break;
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue() + "\t\t");
break;
}
}
System.out.println("");
}
file.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#Test(dataProvider = "DP1")
public void LoginTest() {
driver.findElement(By.id("username")).sendKeys("A");
}

Resources