I am using eclipse, selenium web driver, apache POI, java. I am very new to this and java.
I have xls file with 3 columns: email, pw, result. I have 3 rows of data. Result column is blank.
Each iteration, script should read email and pw and then perform action. Then write result in Result column.
Continue until it reaches the last row.
I hard coded the column number and it works. I am not able to figure out how to find the column number with header "result" and then how to write in the cell for the corresponding row.
File file = new File("C://dd.xls");
try {
// Open the Excel file
FileInputStream fis = new FileInputStream(file);
// Access the required test data sheet
HSSFWorkbook wb = new HSSFWorkbook(fis);
HSSFSheet sheet = wb.getSheet("Sheet1");
int TotalRow;
int TotalCol;
TotalRow = sheet.getLastRowNum();
TotalCol = sheet.getRow(0).getLastCellNum();
System.out.println("row " + TotalRow + " col " + TotalCol);
// Loop through all rows in the sheet
// Start at row 1 as row 0 is our header row
for(int count = 1;count<=sheet.getLastRowNum();count++){
//for(int col = 1;col<=TotalCol;col++){
HSSFRow row = sheet.getRow(count);
System.out.println("Running test case " + row.getCell(0).toString() + " " + row.getCell(1).toString());
HSSFCell hSSFCell = row.getCell(TotalCol-1);
String value = count + "aa";
hSSFCell.setCellValue(value);}
// }
fis.close();
FileOutputStream outputStream = new FileOutputStream(file);
wb.write(outputStream);
outputStream.close();
} catch (IOException e) {
System.out.println("Test data file not found");
}
https://drive.google.com/open?id=1jqefYaffunknolrj6i4SXOoq2LiKT3xTgSsdzaxsBfQ
HSSFWorkbook wb = new HSSFWorkbook(fis);
HSSFSheet sheet = wb.getSheet("Sheet1");
int TotalRow;
int TotalCol;
TotalRow = sheet.getLastRowNum();
HSSFRow headerRow = sheet.getRow(0);
String result = "";
int resultCol = -1;
for (Cell cell : headerRow){
result = cell.getStringCellValue();
if (result.equals("Result"){
resultCol = cell.getColumnIndex();
break;
}
}
if (resultCol == -1){
System.out.println("Result column not found in sheet");
return;
}
System.out.println("row " + TotalRow + " col " + TotalCol);
// Loop through all rows in the sheet
// Start at row 1 as row 0 is our header row
for(int count = 1;count<=sheet.getLastRowNum();count++){
HSSFRow row = sheet.getRow(count);
System.out.println("Running test case " + row.getCell(0).toString() + " " + row.getCell(1).toString());
HSSFCell hSSFCell = row.getCell(resultCol);
String value = count + "aa";
hSSFCell.setCellValue(value);}
// }
fis.close();
FileOutputStream outputStream = new FileOutputStream(file);
wb.write(outputStream);
outputStream.close();
Related
I am new to Selenium and I am trying to write a code to write data into excel. This code is working. However, it just write on the second row. When I change the value of "String FieldName1 to 3" it doesn't write on the next row. I change the value of header = spreadsheet.createRow(0); to (1) it did write to next row, but it is a pain to do it every time I run my test. What I need is to write the data to the next ROW everytime I run it and change the value of "String FieldName1 to 3". THANKS IN ADVANCE!
Selenium > Java > Maven
public class testBed2 {
#Test
public void writeExcel() throws IOException{
FileInputStream fis = new FileInputStream("C:\\Users\\ExportExcel.xlsx");
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet spreadsheet = workbook.createSheet( "TestData");
XSSFRow header;
header = spreadsheet.createRow(0);
header.createCell(0).setCellValue("FieldName1");
header.createCell(1).setCellValue("FieldName2");
header.createCell(2).setCellValue("FieldName3");
int rowNumber = 1;
Row row = spreadsheet.getRow(0);
//Column Count
int colCount = row.getLastCellNum();
for (int j = 0; j < colCount; j++) {
System.out.println("Col Count : " + j);
//Row Count
int rowCount = spreadsheet.getLastRowNum() + 1;
for (int i = 0; i < rowCount; i++) {
XSSFRow currentRow = spreadsheet.createRow(rowNumber);
System.out.println("Row Count : " + i);
String FieldName1 = "NAME1";
String FieldName2 = "NAME2";
String FieldName3 = "NAME3";
currentRow.createCell(0).setCellValue(FieldName1);
currentRow.createCell(1).setCellValue(FieldName2);
currentRow.createCell(2).setCellValue(FieldName3);
FileOutputStream fos = new FileOutputStream("C:\\Users\\ExportExcel.xlsx");
workbook.write(fos);
fos.close();
}
}
}
}
I think the reason why your code write just second row is, your close code is in the For loop. If you write close code at the end of {} you will get right answer. :)
I am printing some string values in excel
In excel currently last string is printing, but I need to print them all row by row
Code
for(String a:arrOfStr)
{
System.out.println(a);
//CustomKeywords.'WriteExcel.demoKey'(a)
CustomKeywords.'WriteExcel.demoKey'(a)
}
keyword
#Keyword
public void demoKey(String name) throws IOException{
FileInputStream fis = new FileInputStream("C:\\Users\\lahiruh\\Katalon Studio\\Project Decypha\\Decypha data files\\Demo1.xlsx");
XSSFWorkbook workbook = new XSSFWorkbook(fis);
XSSFSheet sheet = workbook.getSheet("Sheet1");
int rowCount = sheet.getLastRowNum()-sheet.getFirstRowNum();
Row row = sheet.createRow(rowCount+);
Cell cell = row.createCell(0);
cell.setCellType(cell.CELL_TYPE_STRING);
cell.setCellValue(name);
FileOutputStream fos = new FileOutputStream("C:\\Users\\lahiruh\\Katalon Studio\\Project Decypha\\Decypha data files\\Demo1.xlsx");
workbook.write(fos);
fos.close();
Now I can get the output like(overriding each value and giving last string )
I want to see like
Try this
for(int i = 0; i < arrOfStr.size(); i++)
{
String a = arrOfStr[i];
System.out.println(a);
//CustomKeywords.'WriteExcel.demoKey'(a)
CustomKeywords.'WriteExcel.demoKey'(a,i)
}
#Keyword
public void demoKey(String name, int index) throws IOException{
FileInputStream fis = new FileInputStream("path");
XSSFWorkbook workbook = new XSSFWorkbook(fis);
XSSFSheet sheet = workbook.getSheet("Sheet1");
Row row = sheet.createRow(index + 1);
Cell cell = row.createCell(0);
cell.setCellType(cell.CELL_TYPE_STRING);
cell.setCellValue(name);
FileOutputStream fos = new FileOutputStream("path");
workbook.write(fos);
fos.close();
}
}
You have to do in the following manner.
First create a set of rows
Create cell and define the cell data type.
Store the value in the cell
I provide below the structure to store the data row by row.
int rowNumber = 0; // Row number starting with 0
for (i = 0 ; i < 10 ; i++) { //This for loop can be your data set
Row row = sheet.createRow(rowNumber++);
int columnNumber = 0; //Cell or Column number starting with 0
for (j = 0 ; j < 5 ; j++) { //This for loop can be your data set
Cell cell = row.createCell(columnNumber++);
cell.setCellValue("Some string value");
}
}
Here is my activity. I am stuck in activity and need help please.
I need to read data, have them as key and result in a map<>. get keys from user by press button show the result of the key and then another button to add them to the list if user approve it.
public class ExcelReaderActivity extends AppCompatActivity {
public static final String SAMPLE_XLSX_FILE_PATH = "/home/saeid/Documents/ABBREV.xlsx";
public static final Map<String, String> numberDescMap = new HashMap<>();
public final TextView productInput = findViewById(R.id.textView_InputProductNumber);
public final TextView productName = findViewById(R.id.textView_ProductName);
public final Button checkInput = findViewById(R.id.button_GO);
public final Button addInput = findViewById(R.id.button_AddProduct);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.reader_excel);
}
public static void main(String[] args) throws IOException, InvalidFormatException {
// Creating a Workbook from an Excel file (.xls or .xlsx)
Workbook workbook = WorkbookFactory.create(new File(SAMPLE_XLSX_FILE_PATH));
// Retrieving the number of sheets in the Workbook
System.out.println("Workbook has " + workbook.getNumberOfSheets() + " Sheets : ");
// obtain a sheetIterator and iterate over it
Iterator<Sheet> sheetIterator = workbook.sheetIterator();
System.out.println("Retrieving Sheets using Iterator");
while (sheetIterator.hasNext()) {
Sheet sheet = sheetIterator.next();
System.out.println("=> " + sheet.getSheetName());
}
// Getting the Sheet at index zero
Sheet sheet = workbook.getSheetAt(0);
Row rowCount = sheet.getRow(0);
int totalNumberOfRows = sheet.getPhysicalNumberOfRows();
int totalNumberOfColumns = rowCount.getPhysicalNumberOfCells();
System.out.print("number of rows => " + totalNumberOfRows + "\n");
System.out.print("number of columns => " + totalNumberOfColumns + "\n");
// Create a DataFormatter to format and get each cell's value as String
DataFormatter dataFormatter = new DataFormatter();
// 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();
for (int currentRow = 1; currentRow < totalNumberOfRows; currentRow++){
Row row = rowIterator.next();
row = sheet.getRow(currentRow);
Cell cell0 = row.getCell(0);
Cell cell1 = row.getCell(1);
String cellValue0 = dataFormatter.formatCellValue(cell0);
String cellValue1 = dataFormatter.formatCellValue(cell1);
numberDescMap.put(cellValue0,cellValue1);
//System.out.print(currentRow + "- *" + dbNumbers + "*" + "*" + description + "*" + "\n");
}
List<String> dbNumbers = new ArrayList(numberDescMap.keySet());
List<String> description = new ArrayList(numberDescMap.values());
int checkIndex = 1;
for (String mapkeys : dbNumbers){
System.out.println(checkIndex++ + "- " + mapkeys + "==>" +numberDescMap.get(mapkeys) + "\n");
}
// Closing the workbook
workbook.close();
}
}
I need to access Buttons and TextViews after main(). I tried several ways but not succeeded so far.
I need to work with Buttons and TextViews after the result in main. I need the map<> before using them.
I tried make them static as well or define in onCreate() but was not successful. I appreciate any help.
I did this edit after the answer I got
this is the Java file for act as a method
public class FileReader{
private final Activity activity;
public FileReader(Activity activity) {this.activity = activity;
}
public static final String SAMPLE_XLSX_FILE_PATH = "/home/saeid/Documents/ABBREV.xlsx";
public static final Map<String, String> numberDescMap = new HashMap<>();
public Map<String, String> ExcelFileReader() {
// Creating a Workbook from an Excel file (.xls or .xlsx)
Workbook workbook = null;
try {
workbook = WorkbookFactory.create(new File(SAMPLE_XLSX_FILE_PATH));
} catch (IOException e) {
e.printStackTrace();
} catch (InvalidFormatException e) {
e.printStackTrace();
}
// obtain a sheetIterator and iterate over it
Iterator<Sheet> sheetIterator = workbook.sheetIterator();
System.out.println("Retrieving Sheets using Iterator");
while (sheetIterator.hasNext()) {
Sheet sheet = sheetIterator.next();
//System.out.println("=> " + sheet.getSheetName());
}
// Getting the Sheet at index zero
Sheet sheet = workbook.getSheetAt(0);
Row rowCount = sheet.getRow(0);
int totalNumberOfRows = sheet.getPhysicalNumberOfRows();
int totalNumberOfColumns = rowCount.getPhysicalNumberOfCells();
System.out.println("number of rows => " + totalNumberOfRows );
System.out.println("number of columns => " + totalNumberOfColumns );
// Create a DataFormatter to format and get each cell's value as String
DataFormatter dataFormatter = new DataFormatter();
// 1. You can 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();
for (int currentRow = 1; currentRow < totalNumberOfRows; currentRow++) {
Row row = rowIterator.next();
row = sheet.getRow(currentRow);
Cell cell0 = row.getCell(0);
Cell cell1 = row.getCell(1);
String cellValue0 = dataFormatter.formatCellValue(cell0);
String cellValue1 = dataFormatter.formatCellValue(cell1);
numberDescMap.put(cellValue0, cellValue1);
//System.out.print(currentRow + "- *" + dbNumbers + "*" + "*" + description + "*" + "\n");
}
// Closing the workbook
try {
workbook.close();
} catch (IOException e) {
e.printStackTrace();
}
return numberDescMap;
}
}
I did a debug , the workbook is always null and I get null in activity.
and this is how I call it in activity
FileReader fileReader = new FileReader(this);
final Map<String, String> numberDescMap = fileReader.ExcelFileReader();
Make sure you understand the activity lifecycle properly. Checkout this link
You don't need to use public static void main
public class ExcelReaderActivity extends AppCompatActivity {
public static final String SAMPLE_XLSX_FILE_PATH = "/home/saeid/Documents/ABBREV.xlsx";
public static final Map<String, String> numberDescMap = new HashMap<>();
public final TextView productInput ;
public final TextView productName;
public final Button checkInput ;
public final Button addInput;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.reader_excel);
productInput = findViewById(R.id.textView_InputProductNumber);
productName = findViewById(R.id.textView_ProductName);
checkInput = findViewById(R.id.button_GO);
addInput = findViewById(R.id.button_AddProduct);
createWorkbook();
}
createWorkbook(){
// Creating a Workbook from an Excel file (.xls or .xlsx)
Workbook workbook = WorkbookFactory.create(new File(SAMPLE_XLSX_FILE_PATH));
// Retrieving the number of sheets in the Workbook
System.out.println("Workbook has " + workbook.getNumberOfSheets() + " Sheets : ");
// obtain a sheetIterator and iterate over it
Iterator<Sheet> sheetIterator = workbook.sheetIterator();
System.out.println("Retrieving Sheets using Iterator");
while (sheetIterator.hasNext()) {
Sheet sheet = sheetIterator.next();
System.out.println("=> " + sheet.getSheetName());
}
// Getting the Sheet at index zero
Sheet sheet = workbook.getSheetAt(0);
Row rowCount = sheet.getRow(0);
int totalNumberOfRows = sheet.getPhysicalNumberOfRows();
int totalNumberOfColumns = rowCount.getPhysicalNumberOfCells();
System.out.print("number of rows => " + totalNumberOfRows + "\n");
System.out.print("number of columns => " + totalNumberOfColumns + "\n");
// Create a DataFormatter to format and get each cell's value as String
DataFormatter dataFormatter = new DataFormatter();
// 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();
for (int currentRow = 1; currentRow < totalNumberOfRows; currentRow++){
Row row = rowIterator.next();
row = sheet.getRow(currentRow);
Cell cell0 = row.getCell(0);
Cell cell1 = row.getCell(1);
String cellValue0 = dataFormatter.formatCellValue(cell0);
String cellValue1 = dataFormatter.formatCellValue(cell1);
numberDescMap.put(cellValue0,cellValue1);
//System.out.print(currentRow + "- *" + dbNumbers + "*" + "*" + description + "*" + "\n");
}
List<String> dbNumbers = new ArrayList(numberDescMap.keySet());
List<String> description = new ArrayList(numberDescMap.values());
int checkIndex = 1;
for (String mapkeys : dbNumbers){
System.out.println(checkIndex++ + "- " + mapkeys + "==>" +numberDescMap.get(mapkeys) + "\n");
}
// Closing the workbook
workbook.close();
}
}
You can use all the views instance inside createWorkbook method
Do like this
public class ExcelReaderActivity extends AppCompatActivity {
public static final String SAMPLE_XLSX_FILE_PATH = "/home/saeid/Documents/ABBREV.xlsx";
public static final Map<String, String> numberDescMap = new HashMap<>();
private TextView productInput, productName ;
private Button checkInput , addInput ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.reader_excel);
productName = findViewById(R.id.textView_ProductName);
productInput = findViewById(R.id.textView_InputProductNumber);
checkInput = findViewById(R.id.button_GO);
addInput = findViewById(R.id.button_AddProduct);
workBookCalculation();
}
public void workBookCalculation() throws IOException, InvalidFormatException {
// Creating a Workbook from an Excel file (.xls or .xlsx)
Workbook workbook = WorkbookFactory.create(new File(SAMPLE_XLSX_FILE_PATH));
// Retrieving the number of sheets in the Workbook
System.out.println("Workbook has " + workbook.getNumberOfSheets() + " Sheets : ");
// obtain a sheetIterator and iterate over it
Iterator<Sheet> sheetIterator = workbook.sheetIterator();
System.out.println("Retrieving Sheets using Iterator");
while (sheetIterator.hasNext()) {
Sheet sheet = sheetIterator.next();
System.out.println("=> " + sheet.getSheetName());
}
// Getting the Sheet at index zero
Sheet sheet = workbook.getSheetAt(0);
Row rowCount = sheet.getRow(0);
int totalNumberOfRows = sheet.getPhysicalNumberOfRows();
int totalNumberOfColumns = rowCount.getPhysicalNumberOfCells();
System.out.print("number of rows => " + totalNumberOfRows + "\n");
System.out.print("number of columns => " + totalNumberOfColumns + "\n");
// Create a DataFormatter to format and get each cell's value as String
DataFormatter dataFormatter = new DataFormatter();
// 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();
for (int currentRow = 1; currentRow < totalNumberOfRows; currentRow++){
Row row = rowIterator.next();
row = sheet.getRow(currentRow);
Cell cell0 = row.getCell(0);
Cell cell1 = row.getCell(1);
String cellValue0 = dataFormatter.formatCellValue(cell0);
String cellValue1 = dataFormatter.formatCellValue(cell1);
numberDescMap.put(cellValue0,cellValue1);
//System.out.print(currentRow + "- *" + dbNumbers + "*" + "*" + description + "*" + "\n");
}
List<String> dbNumbers = new ArrayList(numberDescMap.keySet());
List<String> description = new ArrayList(numberDescMap.values());
int checkIndex = 1;
for (String mapkeys : dbNumbers){
System.out.println(checkIndex++ + "- " + mapkeys + "==>" +numberDescMap.get(mapkeys) + "\n");
}
// Closing the workbook
workbook.close();
}
}
And use textview any where in the activity;
i have an excel file with merged and formula cell which is using the VLOOKUP(B16,Data!$A$2:$C$7,3,0). In specific cell $40 is appearing as value. but when i try to read the value it is reading only 40 and skipping the $ part.
public static void main(String[] args) {
try {
String excelFilePath = "D:\\test\\1_sample1_UA Logo Order form update on 2016-12-06.xls";
InputStream input = new BufferedInputStream(new FileInputStream(
excelFilePath));
POIFSFileSystem fs = new POIFSFileSystem(input);
HSSFWorkbook workbook = new HSSFWorkbook(fs);
workbook.setForceFormulaRecalculation(true);
Sheet sheet = workbook.getSheetAt(3);
Row row = sheet.getRow(15);
Cell cell = row.getCell(7);
for (int i = 0; i < sheet.getNumMergedRegions(); i++) {
CellRangeAddress region = sheet.getMergedRegion(i); // Region of
// merged
// cells
int colIndex = region.getFirstColumn();
int rowNum = region.getFirstRow();
if (region.isInRange(15, 7)) {
CellReference cellReference = new CellReference("H15");
Row row2 = sheet.getRow(cellReference.getRow());
Cell cell2 = row2.getCell(cellReference.getCol());
// formulla evaluato
FormulaEvaluator forEvaluator = workbook
.getCreationHelper().createFormulaEvaluator();
workbook.getCreationHelper().createFormulaEvaluator()
.evaluateAll();
workbook.setForceFormulaRecalculation(true);
CellValue cellValue = forEvaluator.evaluate(cell2);
System.out.println("cell string value2 :: "
+ cellValue.formatAsString());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
I am doing a java application (J2SE) which I have to generate a excel document (.xls). I did generate the file but I am not able to change the cell width dynamically according to the content which is having the maximum length in the same cell.
Here is my coding...
try {
ResultSet rs = com.dss.system.DBORCL.search("sql statement");
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("Excel Sheet");
HSSFRow rowhead = sheet.createRow((short) 0);
rowhead.createCell((short) 0).setCellValue("Site");
rowhead.createCell((short) 1).setCellValue("Part No");
rowhead.createCell((short) 2).setCellValue("Part Description");
int index = 1;
while (rs.next()) {
HSSFRow row = sheet.createRow((short) index);
row.createCell((short) 0).setCellValue(rs.getString("site"));
row.createCell((short) 1).setCellValue(rs.getString("part_no"));
row.createCell((short) 1).setCellValue(rs.getString("description"));
index++;
}
FileOutputStream fileOut = new FileOutputStream("F:\\IFS\\IFSDOC" + txtPLCode.getText() + "[" + currentDate + "-" + usesecond + "]" + ".xls");
wb.write(fileOut);
fileOut.close();
System.out.println("Data is saved in excel file.");
// rs.close();
sheet.autoSizeColumn(0) //for first column
sheet.autoSizeColumn(1) //for second column ... etc
Refer: http://poi.apache.org/spreadsheet/quick-guide.html#Autofit