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);
}
}
Related
I have created an excel file sheet with Apache POI. And now I need convert it to PDF. I want to use iText, but I want copy the values and not the formula to pdf.
How can i avoid that formula in my pdf file.
public class pdfExcelTest {
public static void main(String[] args) throws IOException {
// source file whit formula in cells
String file = "c:/my-excel-sheet.xls";
try {
if (file != null) {
FileInputStream fileInputStream = new FileInputStream(file);
HSSFWorkbook workbook = new HSSFWorkbook(fileInputStream);
/*
* ==================================================================
* Iterating
* over all the rows and columns in a Sheet (Multiple ways)
* ==================================================================
*/
// Getting the Sheet at index zero
Sheet sheet = workbook.getSheetAt(0);
// Create a DataFormatter to format and get each cell's value as String
DataFormatter dataFormatter = new DataFormatter();
// landscape format
Document document = new Document(PageSize.A4.rotate());
// portrait format
// Document document = new Document(PageSize.A4);
try {
PdfWriter.getInstance(document, new FileOutputStream("z:/excel2pdfTest.pdf"));
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
document.open();
//the table has 26 columns
PdfPTable table = new PdfPTable(26);
FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
// obtain a rowIterator and columnIterator and iterate over them
System.out.println("\n\nIterating over Rows and Columns using Iterator\n");
Iterator<Row> rowIterator = sheet.rowIterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
// Now let's iterate over the columns of the current row
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
}
String cellValue = dataFormatter.formatCellValue(cell);
// i think i must add different cases for CellTypes String, Values and formula
// and then to build diffent constructor for my cell1
System.out.print(cell + "\t");
Phrase cell1 = Phrase.getInstance(cellValue);
table.addCell(cell1);
}
System.out.println();
}
try {
document.add(table);
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// the document can also have one or more pages - depents how many sheets in my excel file so I must define another table
document.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
My code is not working, it always shows the above mentioned exception.
but I can always see the tmp file being generated.
here is the code, can someone please suggest something:
FileInputStream fis =null;
try{
fis= new FileInputStream(new File("/home/amar/Desktop/new/abc.xls"));
Workbook wb = new org.apache.poi.xssf.usermodel.XSSFWorkbook(fis);
int numOfSheets = wb.getNumberOfSheets();
System.out.println("bhargo num of sheets is " + numOfSheets);
for(int i=0; i<numOfSheets; i++){
org.apache.poi.ss.usermodel.Sheet sheet = wb.getSheetAt(i);
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext())
{
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = (Cell) cellIterator.next();
if (cell.getCellType() == cell.CELL_TYPE_STRING) {
System.out.println("bhargo cell value is " + cell.getStringCellValue().trim());
}
}
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
System.out.println("bhargo, closing the stream");
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
There are a number of issues here:
fis= new FileInputStream(new File("/home/amar/Desktop/new/abc.xls"));
Workbook wb = new org.apache.poi.xssf.usermodel.XSSFWorkbook(fis);
Firstly, as explained in the Apache POI documentation, don't use an InputStream if you have a file! It's slower and uses more memory
Secondly, XSSF is the code for working with .xlsx files, but your file is a .xls one, so that won't work.
Thirdly, Apache POI has code which will automatically work out what kind of file yours is, and create the appropriate workbook for you
Your code should therefore instead be
Workbook wb = WorkbookFactory.create(new File("/home/amar/Desktop/new/abc.xls"));
This will create the right kind of workbook, direct from the file
I was able to solve my problem.
I am working on linux so it was saving the file in the older version of excel
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;
}
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");
}
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.