I want to write the webtable values in excel . I tried it with list but its not writing in the correct format.Its writing all the values in the row only.
ArrayList<String> Storetablevalues = new ArrayList<String>();
WebDriver driver = new FirefoxDriver();
#BeforeTest
public void setup() throws Exception {
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.get("URL");
}
#Test
public void run() throws Exception {
/* driver.findElement(By.xpath(".//*[#id='results']/div/a")).click(); */
Thread.sleep(9000);
System.out.println("Values are loaded");
int Row_count = driver.findElements(By.xpath("//*[#id='assetsTable']/tbody/tr")).size();
System.out.println("Number Of Rows = " + Row_count);
// Get number of columns In table.
int Col_count = driver.findElements(By.xpath("//*[#id='assetsTable']/tbody/tr[2]/td")).size();
System.out.println("Number Of Columns = " + Col_count);
// divided xpath In three parts to pass Row_count and Col_count values.
String first_part = "//*[#id='assetsTable']/tbody/tr[";
String second_part = "]/td[";
String third_part = "]";
String[][] arr = new String[Row_count][Col_count]; // Used for loop for
// number of rows.
for (int i = 2; i <= Row_count; i++) {
// Used for loop for number of columns.
for (int j = 1; j <= Col_count; j++) {
// Prepared final xpath of specific cell as per values of i and
// j.
String final_xpath = first_part + i + second_part + j + third_part;
// Will retrieve value from located cell and print It.
String Table_data = driver.findElement(By.xpath(final_xpath)).getText();
Storetablevalues.add(Table_data);
System.out.print(Table_data + " ");
}
System.out.println("");
System.out.println("");
}
}
public void WriteXL() throws Exception {
// Write a xl
try {
File exlFile = new File("C:/Users/Kishor/Desktop/gtmetrix.xls");
WritableWorkbook writableWorkbook = Workbook.createWorkbook(exlFile);
WritableSheet writableSheet = writableWorkbook.createSheet("Sheet2", 0);
Label Header_Url_label = new Label(0, 0, "URL");
Label Header_Image_label = new Label(1, 0, "Link Check Status");
writableSheet.addCell(Header_Url_label);
writableSheet.addCell(Header_Image_label);
for (int i = 0; i < Storetablevalues.size(); i++) {
int j = i + 1;
Label labelURL = new Label(0, j, Storetablevalues.get(i));
writableSheet.addCell(labelURL);
}
// Write and close the workbook
writableWorkbook.write();
writableWorkbook.close();
System.out.println("Xls Writer...");
} catch (IOException e) {
e.printStackTrace();
} catch (RowsExceededException e) {
e.printStackTrace();
} catch (WriteException e) {
e.printStackTrace();
}
}
}
This is my console Output I want to write in this format in excle
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
public class TableToExcel {
String[][] tableVal;
int rowCount,columnCount;
WebDriver driver = new FirefoxDriver();
private static final String FILE_NAME = "C:/MyFirstExcel.xls";
//https://www.w3schools.com/html/tryit.asp?filename=tryhtml_table_intro
#BeforeClass
public void getTableSize(){
driver.get("https://www.w3schools.com/html/tryit.asp?filename=tryhtml_table_intro");
driver.switchTo().frame("iframeResult");
//get Row size
List<WebElement> row = driver.findElements(By.xpath(".//table/tbody/tr"));
//get Column size
List<WebElement> column = driver.findElements(By.xpath(".//table/tbody/tr/th"));
rowCount = row.size();
columnCount = column.size();
System.out.println("Row :"+rowCount+" Clounm :"+columnCount);
tableVal = new String[rowCount][columnCount];
}
#Test
public void test() throws IOException{
for(int i =1 ; i <= rowCount ; i++ ){
for(int j =1 ; j <= columnCount ; j++ ) {
if(i == 1) {
//Get header value
tableVal[i - 1][j - 1] = driver.findElement(By.xpath(".//table/tbody/tr[" + i + "]/th[" + j + "]")).getText();
System.out.println(driver.findElement(By.xpath(".//table/tbody/tr[" + i + "]/th[" + j + "]")).getText());
}
else{
//get table data values
tableVal[i-1][j-1] =driver.findElement(By.xpath(".//table/tbody/tr["+i+"]/td["+j+"]")).getText();
System.out.println(driver.findElement(By.xpath(".//table/tbody/tr["+i+"]/td["+j+"]")).getText());
}
}
}
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Datatypes in Java");
int rowNum = 0;
System.out.println("Creating excel");
for (Object[] datatype : tableVal) {
Row row = sheet.createRow(rowNum++);
int colNum = 0;
for (Object field : datatype) {
Cell cell = row.createCell(colNum++);
if (field instanceof String) {
cell.setCellValue((String) field);
} else if (field instanceof Integer) {
cell.setCellValue((Integer) field);
}
}
}
try {
FileOutputStream outputStream = new FileOutputStream(FILE_NAME);
workbook.write(outputStream);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
workbook.close();
}
System.out.println("Done");
}
}
Related
I am using iText 7.1.15 in combination with Apache POI 4.1.1 to create a PDF from an Excel sheet.
The rows in the sheet are set to a specific height in centimeters to fit correctly on an A4 page when printed.
However when I set the cell height via iText and have a look at the result the row in the PDF table isn't exactly as high as in Excel.
I am using org.apache.poi.ss.usermodel.Row.getHeightInPoints() and set this value to my PDF table cell using com.itextpdf.layout.element.Cell.setHeight().
Inspecting the result however the row height in my PDF is slightly different than expected.
And some content (the last row in my sample) event gets truncated (I guess because the cell isn't high enough)...
What am I doing wrong here?
You can find the complete sample here at Github
PDF:
Excel:
for (int rowNum = 0; rowNum <= sheet.getLastRowNum(); rowNum++) {
Row row = sheet.getRow(rowNum);
if (row == null) {
continue;
}
float heightInPoints = row.getHeightInPoints();
System.out.println("Row: " + (rowNum + 1) + ": " + heightInPoints + "pt = " + heightInPoints * PT_TO_CM + "cm");
for (int cellNum = 0; cellNum < numCols; cellNum++) {
Cell cell = row.getCell(cellNum, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
com.itextpdf.layout.element.Cell pdfCell = new com.itextpdf.layout.element.Cell();
pdfCell.add(new Paragraph(cell.getStringCellValue()));
pdfCell.setHeight(heightInPoints);
pdfCell.setBorder(new SolidBorder(0.5f));
table.addCell(pdfCell);
}
}
package com.gi.itext;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.borders.SolidBorder;
import com.itextpdf.layout.element.AreaBreak;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.property.AreaBreakType;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
public class App {
private static final String OUTPUT = "./target/output.pdf";
private static final String INPUT = "/input.xlsx";
private static final float PT_TO_CM = 0.0352778f;
public static void main(String[] args) {
new App().run();
}
public void run() {
File file = new File(OUTPUT);
file.getParentFile().mkdirs();
try (InputStream is = getClass().getResourceAsStream(INPUT);
Workbook workbook = new XSSFWorkbook(is)) {
PdfDocument pdfDoc;
try {
pdfDoc = new PdfDocument(new PdfWriter(OUTPUT));
} catch (FileNotFoundException e) {
e.printStackTrace();
return;
}
pdfDoc.addNewPage();
Document doc = new Document(pdfDoc, PageSize.A4);
for (int sheetNum = 0; sheetNum < workbook.getNumberOfSheets(); sheetNum++) {
Sheet sheet = workbook.getSheetAt(sheetNum);
if (sheetNum > 0) {
doc.add(new AreaBreak(AreaBreakType.NEXT_PAGE));
}
int numCols = getNumberOfColumns(sheet);
float[] columnWidth = new float[numCols];
for (int j = 0; j < numCols; j++) {
float columnWidthInPixels = sheet.getColumnWidthInPixels(j);
double columnWidthInPoints = columnWidthInPixels * 0.75d;
columnWidth[j] = (float) columnWidthInPoints;
}
Table table = new Table(columnWidth);
table.useAllAvailableWidth();
for (int rowNum = 0; rowNum <= sheet.getLastRowNum(); rowNum++) {
Row row = sheet.getRow(rowNum);
if (row == null) {
continue;
}
float heightInPoints = row.getHeightInPoints();
System.out.println("Row: " + (rowNum + 1) + ": " + heightInPoints + "pt = " + heightInPoints * PT_TO_CM + "cm");
for (int cellNum = 0; cellNum < numCols; cellNum++) {
Cell cell = row.getCell(cellNum, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
com.itextpdf.layout.element.Cell pdfCell = new com.itextpdf.layout.element.Cell();
pdfCell.add(new Paragraph(cell.getStringCellValue()));
pdfCell.setHeight(heightInPoints);
pdfCell.setBorder(new SolidBorder(0.5f));
table.addCell(pdfCell);
}
}
doc.add(table);
}
doc.close();
pdfDoc.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private int getNumberOfColumns(Sheet sheet) {
int firstRowNum = sheet.getFirstRowNum();
int lastRowNum = sheet.getLastRowNum();
for (int rowNum = firstRowNum; rowNum < lastRowNum; rowNum++) {
Row row = sheet.getRow(rowNum);
if (row == null) {
continue;
}
if (row.getLastCellNum() > -1) {
return row.getLastCellNum();
}
}
return -1;
}
}
I am getting error while run this application. In the sheet.addMergedRegion(cellRangeAddress) line getting error due to the four args are mismatching. Could anyone help me out?
import com.boeing.models.BDIPContent;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import java.io.FileOutputStream;
import java.io.IOException;
#Slf4j
public class BDIPExcelGenerateMerge {
public static void main(String[] args) {
log.info("BDIPExcelGenerateMerge: main() started");
String[] excelHeader = {"CEF", "Input File", "RDC", "Data Subject", "Main Segment", "Key
Field", "Key Field Value", "Reason"};
String[][] recordsData = {
{"CEF1", "0520_B777_FMR.pdf (view)", "VBI", "FH", "AID segment", "AIN1", "A23412",
"In file Duplicate Record"},
{"CEF1", "0520_B777_FMR.pdf (view)", "VBI", "FH", "AIDI segment", "AIN1",
"A23413", "In file Duplicate Record"},
{"CEF1", "0820_B777_FMR.pdf(view)", "VBI", "FH", "AID segment", "AIN2", "A23414",
"Not convertible dates are given in input records\n"},
{"CEF2", "CR102020_LAN_17.xls(View)", "VBI", "SI", "AIDO segment", "AIN2",
"A23416", "Not convertible dates are given in input records\n"},
{"CEF2", "CR102020_LAN_17.xls(View)", "VBI", "SI", "AID segment", "AIN3",
"A23417", "In file Duplicate Record-1"},
{"CEF2", "2.pdf(view)", "VBI", "SI", "AIDO segment", "AIN4", "A23418", "In file
Duplicate Record"},
{"CEF3", "3.pdf(view)", "LAN", "CR", "AID segment", "AIN4", "A23419", "In file
Duplicate Record"},
{"CEF3", "3.pdf(view)", "LAN", "CR", "AID9 segment", "AIN5", "A234110", "In file
Duplicate Record"},
{"CEF1", "0520_B777_FMR1.pdf (view)", "VBI67", "FH", "AID segment-1", "AIN1",
"A23412", "In file Duplicate Record"}
};
log.info("invoking generateExcelMerge() method");
generateExcelMerge(excelHeader, recordsData);
}
public static void generateExcelMerge(String[] excelHeader, String[][] recordsData) {
log.info("generateExcelMerge: method invoking started.");
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Rejected_Sheet");
// Create header CellStyle
Font headerFont = workbook.createFont();
headerFont.setBold(true);
headerFont.setColor(IndexedColors.BLACK.index);
HSSFRow row = sheet.createRow((int) 0);
HSSFCellStyle style = workbook.createCellStyle();
style.setAlignment(HorizontalAlignment.CENTER);
style.setVerticalAlignment(VerticalAlignment.JUSTIFY);
style.setBorderBottom(BorderStyle.THIN);
style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
style.setBorderRight(BorderStyle.THIN);
style.setRightBorderColor(IndexedColors.BLUE.getIndex());
style.setBorderTop(BorderStyle.THIN);
style.setTopBorderColor(IndexedColors.BLACK.getIndex());
log.info("generateExcelMerge: setting column width");
for (int i = 0; i < excelHeader.length; i++) {
HSSFCell cell = row.createCell(i);
cell.setCellValue(excelHeader[i]);
cell.setCellStyle(style);
sheet.setColumnWidth(i, 20 * 200);
}
log.info("generateExcelMerge: setting column style");
for (int i = 0; i < recordsData.length; i++) {
row = sheet.createRow(i + 1);
for (int j = 0; j < recordsData[0].length; j++) {
HSSFCell cell = row.createCell(j);
cell.setCellStyle(style);
}
}
int rowNumber = recordsData.length;//Rows
int columnNumber = recordsData[0].length; // number of columns
int index = 0;
for (int i = 0; i < columnNumber; i++) {
index = 0;
for (int j = 0; j < rowNumber; j++) {
BDIPContent bdipContent = new BDIPContent();
bdipContent.setContent(recordsData[j][i].toString());
if (j == rowNumber - 1) {
//System.out.println(((short) index + 1)+" : "+((short) i)+" : "+((short) j +
1)+" : "+((short) i));
// if( (((short) index + 1) == ((short) i)) && (((short) j + 1) ==
((short)
i))) {
// break;
// }
log.info("generateExcelMerge: cell merge start");
CellRangeAddress cellRangeAddress = new CellRangeAddress((short) index + 1 ,
(short) j + 1, (short) i, (short) i);
sheet.addMergedRegion(cellRangeAddress);
sheet.getRow(index + 1).getCell(i).setCellValue(bdipContent.getContent());
} else {
bdipContent.setOldContent(recordsData[j + 1][i].toString());
}
if (!bdipContent.getContent().equals(bdipContent.getOldContent())) {
// if( (((short) index + 1) == ((short) i)) && (((short) j + 1) ==
((short)
i))) {
// break;
// }
log.info("generateExcelMerge: cross checking content with oldContent");
//System.out.println("oldContent: "+((short) index + 1)+" : "+((short) i)+"
: "+((short) j + 1)+" : "+((short) i));
CellRangeAddress cellRangeAddress = new CellRangeAddress((short) index + 1 ,
(short) j + 1 , (short) i, (short) i);
sheet.addMergedRegion(cellRangeAddress);
sheet.getRow(index + 1).getCell(i).setCellValue(bdipContent.getContent());
if (j == rowNumber - 2) {
// the last line of the previous line are not the same
sheet.getRow(index +
2).getCell(i).setCellValue(bdipContent.getOldContent());
break;
}
index = j + 1;
}
}
}
//Generate a temporary file
FileOutputStream fileOutputStream = null;
String fileName =
"D:\\BdipExcelMergeRejectedStatus\\src\\resources\\RecordRejectedStatus.xls";
try {
fileOutputStream = new FileOutputStream(fileName);
workbook.write(fileOutputStream);
System.out.println(fileName);
} catch (IOException e) {
log.error("generateExcelMerge: catch() " + e.getStackTrace());
e.printStackTrace();
} finally {
try {
fileOutputStream.flush();
fileOutputStream.close();
} catch (IOException e) {
log.error("generateExcelMerge: catch() " + e.getStackTrace());
e.printStackTrace();
}
}
log.info("generateExcelMerge: method invoking End.");
}
}
model as:
public class BDIPContent {
private String content;
private String oldContent;
public String getOldContent() {
return oldContent;
}
public void setOldContent(String oldContent) {
this.oldContent = oldContent;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
Getting output:
Help me out to resolve the issue.
Much appreciated, thanks in advance.
I'm trying to import data from Excel file to automate a large amount of data but I got the error "Cannot get a STRING value from a NUMERIC cell" as some of the cells has a numeric values and others has a text value.I need to extract all data and insert it as inputs for the page fields. i got the error stating from
signin_credentials[i][2] = configuration.getData(0, i, 5);
signin_credentials[i][3] = configuration.getData(0, i, 6);
Here is my code:
import org.apache.poi.ss.usermodel.CellType;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class ExcelExample {
WebDriver driver;
#Test(dataProvider = "testdata")
public void demoClass(String NameEN, String NameAr, String ServiceCode, String min, String max)
throws InterruptedException {
//System.setProperty("webdriver.chrome.driver", "Path of Chrome Driver");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://192.168.1.130/Account/Login");
driver.findElement(By.name("UsernameOrEmailAddress")).sendKeys("admin");
driver.findElement(By.name("Password")).sendKeys("P#ssw0rd");
driver.findElement(By.id("LoginButton")).click();
Thread.sleep(5000);
driver.findElement(By.partialLinkText("Services")).click();
Thread.sleep(500);
//click on service list
driver.findElement(By.partialLinkText("Service List")).click();
Thread.sleep(500);
//click on rotate circle
driver.findElement(By.xpath("/html/body/section[2]/div/div[1]/div/div/div[2]/div[2]/a[4]/span/span")).click();
Thread.sleep(2000);
//click on +
driver.findElement(By.xpath("/html/body/section[2]/div/div[1]/div/div/div[2]/div[2]/a[3]/span")).click();
Thread.sleep(1000);
//write on service name
driver.findElement(By.id("Name")).sendKeys(NameEN);
Thread.sleep(500);
//write on service name Arabic
driver.findElement(By.id("NameAr")).sendKeys(NameAr);
WebElement drodown = driver.findElement(
By.xpath("//*[#id=\"ServiceCreateForm\"]/div/div/div/div[2]/div[3]/div[1]/div/div/button"));
drodown.click();
WebElement range = driver.findElement(
By.xpath("//*[#id=\"ServiceCreateForm\"]/div/div/div/div[2]/div[3]/div[1]/div/div/div/ul/li[2]/a"));
range.click();
//select min amount
driver.findElement(By.name("MinValue")).sendKeys(min);
//select max amount
driver.findElement(By.name("MaxValue")).sendKeys(max);
//driver.findElement(By.xpath("//*[#id=\"ServiceCreateForm\"]/div/div/div/div[2]/div[7]/div/button")).click();
}
#AfterMethod
void ProgramTermination() {
//driver.quit();
}
#DataProvider(name = "testdata")
public Object[][] testDataExample() {
ReadExcelFile configuration = new ReadExcelFile("C:\\Users\\Desktop\\file.xlsx");
int rows = configuration.getRowCount(0);
Object[][] signin_credentials = new Object[rows][5];
for (int i = 0; i < rows; i++) {
signin_credentials[i][0] = configuration.getData(0, i, 3);
signin_credentials[i][1] = configuration.getData(0, i, 4);
signin_credentials[i][2] = configuration.getData(0, i, 5);
signin_credentials[i][3] = configuration.getData(0, i, 6);
}
return signin_credentials;
}
}
and here is my excel class:
package Login;
import java.io.File;
import java.io.FileInputStream;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ReadExcelFile {
XSSFWorkbook work_book;
XSSFSheet sheet;
public ReadExcelFile(String excelfilePath) {
try {
File s = new File(excelfilePath);
FileInputStream stream = new FileInputStream(s);
work_book = new XSSFWorkbook(stream);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public String getData(int sheetnumber, int row, int column) {
sheet = work_book.getSheetAt(sheetnumber);
String data = sheet.getRow(row).getCell(column).getStringCellValue();
return data;
}
public int getRowCount(int sheetIndex) {
int row = work_book.getSheetAt(sheetIndex).getLastRowNum();
row = row + 1;
return row;
}
}
try ((xssfcell) sheet.getRow(row).getCell(column)).getRawValue()
Which actually worked for me in a differnt way
You dont really need to use the multiple if conditions.
Improved method getData(int sheetnumber, int row, int column) that returns always data as a String or null:
// add this two imports
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.xssf.usermodel.XSSFCell;
...
public String getData(int sheetnumber, int row, int column) {
sheet = work_book.getSheetAt(sheetnumber);
XSSFCell cell = sheet.getRow(row).getCell(column);
String data = null;
if (cell != null) {
CellType cellType = cell.getCellType();
if (cellType.toString() == "STRING") {
data = cell.getStringCellValue();
}
else if (cellType.toString() == "NUMERIC") {
data = String.valueOf(cell.getNumericCellValue());
}
else if (cellType.toString() == "FORMULA") {
data = cell.getCellFormula();
}
else if (cellType.toString() == "BOOLEAN") {
data = String.valueOf(cell.getBooleanCellValue());
}
else if (cellType.toString() == "ERROR") {
// let data be null or assign some value like this
data = "ERROR in sheet nr. " + sheetnumber + " row nr. " + row + " column nr. " + column;
}
else if (cellType.toString() == "BLANK") {
// let data be null or assign some value like this
data = "BLANK cell in sheet nr. " + sheetnumber + " row nr. " + row + " column nr. " + column;
}
else {
// let data be null or assign some value like this
data = "UNKNOWN cell type in sheet nr. " + sheetnumber + " row nr. " + row + " column nr. " + column;
}
}
return data;
}
i am using Apache POI for reading Excel rows and using as needed. In order to Enhance the script for better reusability, how can i search and find a String value in all sheets under Column A and read corresponding row. For Example in Sheet2 ColumnA i have Name called Peter and in ColumnB Date of birth of Peter is 12/18/1984. Can you give code sample to search Peter in ColumnA in Excel work book and return his Date of Birth from ColumnB? Below is the code i am using currently may not suit above criteria.
package com.Sample.GenericFunctionsLibrary;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.apache.commons.io.FileUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DataFormatter;
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.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
public class TestUtil {
public static Xls_Reader excel = null;
public static String path = "./XLFile/Data.xlsx";
public static String mailscreenshotpath;
public static String generateTimeStamp() {
Calendar cal = new GregorianCalendar();
int month = cal.get(Calendar.MONTH); // 3
int year = cal.get(Calendar.YEAR); // 2014
int sec = cal.get(Calendar.SECOND);
int min = cal.get(Calendar.MINUTE);
int date = cal.get(Calendar.DATE);
int day = cal.get(Calendar.HOUR_OF_DAY);
String timestamp = year + "_" + date + "_" + (month + 1) + "_" + day + "_" + min + "_" + sec;
return timestamp;
}
public static boolean isExecutable(String tcid) {
for (int rowNum = 2; rowNum <= excel.getRowCount("Credentials"); rowNum++) {
if (excel.getCellData("Credentials", "TestCase_Name", rowNum).equals(tcid)) {
if (excel.getCellData("Credentials", "runmode", rowNum).equalsIgnoreCase("Y")) {
return true;
} else {
return false;
}
}
}
return false;
}
public static Object[][] getData(String sheetName) {
int rows = excel.getRowCount(sheetName);
int cols = excel.getColumnCount(sheetName);
Object[][] data = new Object[rows - 1][cols];
for (int rowNum = 2; rowNum <= rows; rowNum++) { // 2
for (int colNum = 0; colNum < cols; colNum++) {
data[rowNum - 2][colNum] = excel.getCellData(sheetName, colNum, rowNum); // -2
}
}
return data;
}
public static void zip(String filepath) {
try {
File inFolder = new File(filepath);
File outFolder = new File("Reports.zip");
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(outFolder)));
BufferedInputStream in = null;
byte[] data = new byte[1000];
String files[] = inFolder.list();
for (int i = 0; i < files.length; i++) {
in = new BufferedInputStream(new FileInputStream(inFolder.getPath() + "/" + files[i]), 1000);
out.putNextEntry(new ZipEntry(files[i]));
int count;
while ((count = in.read(data, 0, 1000)) != -1) {
out.write(data, 0, count);
}
out.closeEntry();
}
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
// --------------------------------------Read Data From
// Excel------------------------------------
public static String[][] GetValue(String Pathfile, String sheetName, int startrow) throws IOException {
File excel = new File(Pathfile);
FileInputStream fis = new FileInputStream(excel);
#SuppressWarnings("resource")
XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet ws = wb.getSheet(sheetName);
// System.out.println(startrow);
int colNum = ws.getRow(startrow).getLastCellNum();
// System.out.println(colNum);
String[][] arrays = new String[1][colNum];
for (int i = 0; i < colNum; i++) {
XSSFRow row = ws.getRow(startrow);
XSSFCell cell = row.getCell(i);
arrays[0][i] = cellToString(cell);
// System.out.println(arrays[0][i]);
}
return arrays;
}
// private static String cellToString(XSSFCell cell) {
// Object result;
// int type = cell.getCellType();
//
// switch(type)
// {
// case 0:
// result = cell.getNumericCellValue();
// break;
// case 1:
// result = cell.getStringCellValue();
// break;
// default:
// throw new RuntimeException("there are no support for this type of cell");
// }
private static String cellToString(XSSFCell cell) {
Object result;
int type;
try {
type = cell.getCellType();
} catch (NullPointerException e) {
type = 2;
}
switch (type) {
case Cell.CELL_TYPE_NUMERIC:
DataFormatter formatter = new DataFormatter();
result = formatter.formatCellValue(cell);
break;
case Cell.CELL_TYPE_STRING:
result = cell.getStringCellValue();
break;
case Cell.CELL_TYPE_BLANK:
result = "";
break;
default:
throw new RuntimeException("there are no support for this type of cell");
}
//
return result.toString();
}
}
This method will take a String value for the name to search and return the address for the first record found in the column next to it, assuming that the name is in the first column and the address is in the second column. It will iterate over all sheets as asked. It returns empty String if name is not found. Try/catch block excluded for readability.
public static String findAddressByName(String nameToSearch) {
String fileLocation = "I:\\foo.xlsx";
XSSFWorkbook wb = new XSSFWorkbook(new File(fileLocation));
for (int sheetIndex = 0; sheetIndex < wb.getNumberOfSheets(); sheetIndex++) {
XSSFSheet sheet = wb.getSheetAt(sheetIndex);
for (int rowIndex = 0; rowIndex < sheet.getLastRowNum(); rowIndex++) {
XSSFRow row = sheet.getRow(rowIndex);
if (row != null && row.getCell(0).getStringCellValue().equals(nameToSearch)) {
return row.getCell(1).getRawValue();
}
}
}
return "";
}
I need to read specific column of an excel sheet and then declare the variables in java. The program that I have done reads the entire content of excel sheet. But I need to read a fixed column like C.
This is what I have done:
import java.io.File;
import java.io.IOException;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
public class JavaApplication4
{
private String inputFile;
String[][] data = null;
public void setInputFile(String inputFile)
{
this.inputFile = inputFile;
}
public String[][] read() throws IOException
{
File inputWorkbook = new File(inputFile);
Workbook w;
try
{
w = Workbook.getWorkbook(inputWorkbook);
// Get the first sheet
Sheet sheet = w.getSheet(0);
data = new String[sheet.getColumns()][sheet.getRows()];
// Loop over first 10 column and lines
// System.out.println(sheet.getColumns() + " " +sheet.getRows());
for (int j = 0; j <sheet.getColumns(); j++)
{
for (int i = 0; i < sheet.getRows(); i++)
{
Cell cell = sheet.getCell(j, i);
data[j][i] = cell.getContents();
// System.out.println(cell.getContents());
}
}
for (int j = 0; j < data.length; j++)
{
for (int i = 0; i <data[j].length; i++)
{
System.out.println(data[j][i]);
}
}
}
catch (BiffException e)
{
e.printStackTrace();
}
return data;
}
public static void main(String[] args) throws IOException
{
JavaApplication4 test = new JavaApplication4();
test.setInputFile("C://users/admin/Desktop/Content.xls");
test.read();
}
}
Here is my excel sheet,
From a bowl of chits numbered /#v1#/ to /#v2#/ , a single chit is randomly drawn. Find the probability that the chit drawn is a number that is a multiple of /#v3#/ or /# v4#/?
I need to read this data and by matching the pattern /#v1#1, I need to declare the variables. How can I do this?
What you can do, you should first get all the columns from the sheet by using sheet.getColumns() and store all columns in a list . Then you can match get all values based on columns. or you can get for only column "C".try using below code. let me know if this works.
int masterSheetColumnIndex = sheet.getColumns();
List<String> ExpectedColumns = new ArrayList<String>();
for (int x = 0; x < masterSheetColumnIndex; x++) {
Cell celll = sheet.getCell(x, 0);
String d = celll.getContents();
ExpectedColumns.add(d);
}
LinkedHashMap<String, List<String>> columnDataValues = new LinkedHashMap<String, List<String>>();
List<String> column1 = new ArrayList<String>();
// read values from driver sheet for each column
for (int j = 0; j < masterSheetColumnIndex; j++) {
column1 = new ArrayList<String>();
for (int i = 1; i < sheet.getRows(); i++) {
Cell cell = sheet.getCell(j, i);
column1.add(cell.getContents());
}
columnDataValues.put(ExpectedColumns.get(j), column1);
}
This is the very simple and efficient code and Working as expected
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
public class TestExcelFile {
public static void main(String[] args) {
String envFilePath = System.getenv("AZURE_FILE_PATH");
// upload list of files/directory to blob storage
File folder = new File(envFilePath);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
System.out.println("File " + listOfFiles[i].getName());
Workbook workbook;
//int masterSheetColumnIndex = 0;
try {
workbook = WorkbookFactory.create(new FileInputStream(envFilePath + "\\"+ listOfFiles[i].getName()));
// Get the first sheet.
Sheet sheet = workbook.getSheetAt(0);
//we will search for column index containing string "Your Column Name" in the row 0 (which is first row of a worksheet
String columnWanted = "Column_Name";
Integer columnNo = null;
//output all not null values to the list
List<Cell> cells = new ArrayList<Cell>();
// Get the first cell.
Row row = sheet.getRow(0);
//Cell cell = row.getCell(0);
for (Cell cell : row) {
// Column header names.
//System.out.println(cell.toString());
if (cell.getStringCellValue().equals(columnWanted)){
columnNo = cell.getColumnIndex();
}
}
if (columnNo != null){
for (Row row1 : sheet) {
Cell c = row1.getCell(columnNo);
if (c == null || c.getCellType() == Cell.CELL_TYPE_BLANK) {
// Nothing in the cell in this row, skip it
} else {
cells.add(c);
//System.out.println(c);
}
}
}else{
System.out.println("could not find column " + columnWanted + " in first row of " + listOfFiles[i].getName());
}
} catch (InvalidFormatException | IOException e) {
e.printStackTrace();
}
}
}
}
}
Reading Particular column from excel file
File myFile = new File(path);
FileInputStream fis = new FileInputStream(myFile);
// Finds the workbook instance for XLSX file
XSSFWorkbook myWorkBook = new XSSFWorkbook (fis);
//XSSFWorkbook workBook = new XSSFWorkbook();
//Reading sheet at number 0 in spreadsheet(image attached for reference
Sheet sheet = myWorkBook.getSheetAt(0);
//creating a Sheet object to retrieve object
Iterator<Row> itr = sheet.iterator();//iterating over excel file
while (itr.hasNext())
{
Row row = itr.next();
Iterator<Cell> cellIterator = row.cellIterator();//iterating over each column
//Reading cell in my case column name is ppm
Cell ppmEx= row.getCell(0);
//Cell cell = cellIterator.next();
while (cellIterator.hasNext())
{
Cell cell = cellIterator.next();
//Check the cell type and format accordingly
switch (cell.getCellType())
{
case Cell.CELL_TYPE_NUMERIC:
//System.out.println(cell.getNumericCellValue() + " ");
al.add(cell.getNumericCellValue());
break;
case Cell.CELL_TYPE_STRING:
//System.out.println(cell.getStringCellValue()+" ");
al.add(cell.getStringCellValue());
break;
case Cell.CELL_TYPE_BOOLEAN:
//System.out.println(cell.getBooleanCellValue()+" ");
al.add(cell.getBooleanCellValue());
case Cell.CELL_TYPE_BLANK:
//System.out.println("blank");
al.add("blank");
}
}
System.out.println("-");
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package xlsxreader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
/**
*
* #author khaled
*/
public class XlsxReader {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws FileNotFoundException, IOException, InvalidFormatException {
File file = new File("C:\\Users\\khaled\\Desktop\\myXLSX file.xlsx");
Workbook workbook = WorkbookFactory.create(new FileInputStream(file));
Sheet sheet = workbook.getSheetAt(0);
int column_index_1 = 0;
int column_index_2 = 0;
int column_index_3 = 0;
Row row = sheet.getRow(0);
for (Cell cell : row) {
// Column header names.
switch (cell.getStringCellValue()) {
case "MyFirst Column":
column_index_1 = cell.getColumnIndex();
break;
case "3rd Column":
column_index_2 = cell.getColumnIndex();
break;
case "forth Column":
column_index_3 = cell.getColumnIndex();
break;
}
}
for (Row r : sheet) {
if (r.getRowNum()==0) continue;//hearders
Cell c_1 = r.getCell(column_index_1);
Cell c_2 = r.getCell(column_index_2);
Cell c_3 = r.getCell(column_index_3);
if (c_1 != null && c_1.getCellType() != Cell.CELL_TYPE_BLANK
&&c_2 != null && c_2.getCellType() != Cell.CELL_TYPE_BLANK
&&c_3 != null && c_3.getCellType() != Cell.CELL_TYPE_BLANK) {
System.out.print(" "+c_1 + " " + c_2+" "+c_3+"\n");
}
}
}
}