didnot write in excel sheet - java

i want to write my data in excel.but it didnot write in formatted way
driver.get("https://careernavigator.naukri.com/sales-executive-retail-careers-in-mahindra-and-mahindra-financial-services-15731");
List<WebElement> row = driver.findElements(By.xpath("(//*[name()='svg'])[2]//*[name()='rect' and #height='40']"));
List<WebElement> column = driver.findElements(By.xpath("(//*[name()='svg'])[2]//*[name()='text']//*[name()='tspan' and (#dy=4 or #dy='3.5')]"));
for (int i=0;i<column.size();i++) {
System.out.println(column.get(i).getText());
XSSFRow row1 = sheet.createRow(i);
for(int j=0;j<4;j++)
{
Cell cell1 = row1.createCell(j);
cell1.setCellValue(column.get(j).getText());

The issue appears to be with your for loop structure. A couple of notes, first, on some observations.
You need a high implicit wait here because the site is slow to load the findings.
Your rows xpath finds nothing, but your column xpath works, even though it did not when I ported to Protactor.
I am sketching an alternative using locator by id "f1" and splitting the resulting text, but it turns out that is equivalent to what your xpath "column" finds.
The key here is to know when a new row begins and when the items are no longer really data you want. Rows start when the index is a multiple of 3, since each row has 3 fields (a name and 2 numbers). Stuff about which we do not care begins with the number 1. I did not write code to put the data in Excel, but I indicated where you would.
Here is my code (yours will vary slightly because of where your chrome driver or whichever is located, as well as because you have the Excel sheet pieces):
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class ShonaDriver {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "bin/chromedriver");
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(90, TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.get(
"https://careernavigator.naukri.com/sales-executive-retail-careers-in-mahindra-and-mahindra-financial-services-15731");
/// the row xpath that ws once here found nothing
List<WebElement> column = driver.findElements(
By.xpath("(//*[name()='svg'])[2]//*[name()='text']//*[name()='tspan' and (#dy=4 or #dy='3.5')]"));
int spreadSheetRowNum = 0;
int spreadSheetColumnNum = 0;
WebElement f1 = driver.findElement(By.id("f1"));
for (int i = 0; i < column.size(); i++) {
if (column.get(i).getText().equalsIgnoreCase("1")) {
// reached end of meaningful fields
break;
}
if (i % 3 == 0) {// start of new row
spreadSheetRowNum++;
System.out.println("here create row: " + spreadSheetRowNum);
spreadSheetColumnNum = 1;// assuming excel column A is column 1
} else {
spreadSheetColumnNum++;
}
System.out.println("for column list " + i + " text is:");
System.out.println(column.get(i).getText());
System.out.println("write it to row " + spreadSheetRowNum + " column " + spreadSheetColumnNum);
}
String[] f1Arr = f1.getText().split("\n");
System.out.println("if you prefer to use the f1 array, its contents are:");
for (int i = 0; i < f1Arr.length; i++) {
System.out.println("f1[" + i + "] = " + f1Arr[i]);
}
driver.close();
}
}
and here is the output I get indicating what is there and what you need to do at the various steps:
here create row: 1
for column list 0 text is:
Mahindra and Mahindra Financia..
write it to row 1 column 1
for column list 1 text is:
4.8
write it to row 1 column 2
for column list 2 text is:
2.4
write it to row 1 column 3
here create row: 2
for column list 3 text is:
Tata Motors
write it to row 2 column 1
for column list 4 text is:
5.0
write it to row 2 column 2
for column list 5 text is:
2.6
write it to row 2 column 3
here create row: 3
for column list 6 text is:
Mahindra and Mahindra
write it to row 3 column 1
for column list 7 text is:
4.6
write it to row 3 column 2
for column list 8 text is:
2.9
write it to row 3 column 3
if you prefer to use the f1 array, its contents are:
f1[0] = Mahindra and Mahindra Financia..
f1[1] = 4.8
f1[2] = 2.4
f1[3] = Tata Motors
f1[4] = 5.0
f1[5] = 2.6
f1[6] = Mahindra and Mahindra
f1[7] = 4.6
f1[8] = 2.9
f1[9] = 1
f1[10] = 1
f1[11] = 2
f1[12] = 2
f1[13] = 3
f1[14] = 3
f1[15] = 4
f1[16] = 4
f1[17] = 5
f1[18] = 5
f1[19] = 6
f1[20] = 6
f1[21] = 7
f1[22] = 7
f1[23] = 8
f1[24] = 8
f1[25] = Avg.Exp
f1[26] = Avg.Sal
f1[27] = In lacs
f1[28] = Avg.Exp
f1[29] = Avg.Sal
f1[30] = In lacs
f1[31] = Top Companies
f1[32] = Top Companies
f1[33] = Top Companies
f1[34] = Top Companies
f1[35] = 1.6
f1[36] = 4.9
f1[37] = 2.4
f1[38] = 1.6
f1[39] = 7.0
f1[40] = 2.6
f1[41] = 1.3
f1[42] = 7.2
f1[43] = 2.9
f1[44] = View 22 more Companies.

Related

How to display an Object in a column with apache-poi

I have a big DTO with exactly 234 fields, and I have to display values of each fields of this DTO in a column of an Excel file created with apache-poi.
This is my code :
// Blank workbook
XSSFWorkbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Export values");
// Get the Entity
Simfoot simEntity = simService.findById(simId).get();
Row row = sheet.createRow(0);
row.createCell(1).setCellValue("Consult our values");
// and after this I want to convert my Simfoot object to a column in the third column ( so creteCell(2) ..... ).
I want to have in my first column : nothing , in my second only the String display ( "Consult our values" ) and in my third column I need to have my 234 fields. With an field ( the value of the field ) in one cell. So, 234 rows displaying one value in the third column.
I hope that it is clear.
Thanks a lot for your help.
Using some reflection:
// Blank workbook
XSSFWorkbook workbook = new XSSFWorkbook();
final Sheet sheet = workbook.createSheet("Export values");
// Get the Entity
final Simfoot simEntity = simService.findById(simId).get();
Row row = sheet.createRow(0);
row.createCell(1).setCellValue("Consult our values");
// and after this I want to convert my Simfoot object to a column in the third column ( so creteCell(2) ..... ).
Arrays.stream(simEntity.getClass().getDeclaredMethods())
.filter(m -> m.getName().startsWith("get") && m.getParameterTypes().length == 0 && !void.class.equals(m.getReturnType()))
.forEach(m -> {
try {
Object value = m.invoke(simEntity, null);
Row r = sheet.createRow(sheet.getLastRowNum()+1);
r.createCell(2).setCellValue(value == null ? "" : value.toString());
}
catch (Exception ex) {
// Manage Exception....
}
});
I'll add a method on Simfoot to return all the values:
public List<String> getAllValues() {
return Arrays.asList(getAtt1(), getAtt2(), .. , getAtt234());
}
Then create a row per attribute, and then you can merge the rows of the first 2 columns. Example here with 6 attributes:
int n = 6; // would be 234 for you
XSSFCellStyle styleAlignTop = workbook.createCellStyle();
styleAlignTop.setVerticalAlignment(VerticalAlignment.TOP);
Row row;
for(int i=0; i<n; i++) {
row = sheet.createRow(i);
if(i==0) {
Cell cell = row.createCell(1);
cell.setCellStyle(styleAlignTop);
cell.setCellValue("Consult our values");
}
row.createCell(2).setCellValue(simEntity.getAllValues().get(i));
}
sheet.addMergedRegion(new CellRangeAddress(0, n-1, 0, 0));
sheet.addMergedRegion(new CellRangeAddress(0, n-1, 1, 1));
It shows like this:
Another way to list your attributes would be to use Reflection but I find it very clunky:
Simfoot simEntity = new Simfoot("pap", "pep", "pip", "pop", "pup", "pyp");
for(PropertyDescriptor propertyDescriptor :
Introspector.getBeanInfo(Simfoot.class).getPropertyDescriptors()) {
System.out.println(propertyDescriptor.getReadMethod().invoke(simEntity));
}
Outputs:
pap
pep
pip
pop
pup
pyp
class Simfoot
so you have to filter out getClass and any other unwanted methods and getters

Java code to Search an Excel file with specific date and get the complete row which is matched

I am new to Java coding. I am trying to find a Java code to retrieve the specific rows from an Excel file when it matches with my date. I found some code on the Web but not able to successfully use it for searching the Excel and retrieving the rows.
For example, my Excel sheet contains below
Empno join_date first_name last_name dob
123456 02/24/2017 John Smiths 07/14/1990
324455 02/24/2017 David Conner 12/29/1991
388787 03/14/2017 Sam Brown 04/13/1991
I need to retrieve all rows which matched join_date as '02/24/2017' like below.
123456 02/24/2017 John Smiths 07/14/1990
324455 02/24/2017 David Conner 12/29/1991
Please help.
public void readExcel() throws BiffException, IOException {
String FilePath = "D:\\fake.xls";
FileInputStream fs = new FileInputStream(FilePath);
Workbook wb = Workbook.getWorkbook(fs);
// the access to the sheet
Sheet sh = wb.getSheet("Sheet1");
// To get the number of rows present in sheet
int noOfRows = sh.getRows();
// To get the number of columns present in sheet
int noOfCols = sh.getColumns();
for (int row = 0; row < noOfRows; row++) {
if(sh.getCell(1, row).getContents()==your_date){
for (int row_1 =row ; row_1 < noOfRows; row_1++) {
for (int col = 0; col < noOfCols; col++) {
System.out.print(sh.getCell(col, row).getContents() + "\t");
}
System.out.println();
}
}
}
}
I Hope this will help you
You need to use JXL Library and XLS format file.

Trouble Getting information from html tables in java

I want to get information from the first table inside this site
Link
This its the code i have
Document document = Jsoup.parse(DownloadPage("http://www.transtejo.pt/clientes/horarios" +
"-ligacoes-fluviais/ligacao-barreiro-terreiro-do-paco/#dias-uteis"));
Elements table = document.select("table.easy-table-creator:nth-child(1) tbody");
Elements trAll = table.select("tr");
//For the Table Hour
Elements tr_first = table.select("tr:nth-child(1)");
Element tr = tr_first.get(1);
Elements td = tr.getElementsByTag("td");
for(int i = 0; i < td.size(); i++) {
Log.d("TIME TABLE:"," " + td.get(i).text());
for(int i1 = 1; i1 < trAll.size(); i1++) {
Elements td_inside = trAll.get(i1).getElementsByTag("td");
Log.d("TD INSIDE:"," " + td_inside.get(i).text());
}
}
Right now im being able to get information, the problem its that im getting content from other tables, because all tables class name are the same and im having trouble specifying the table that i need, and im also getting IndexOutOfBoundsException
This its the Log of this
Loglink
The type of log i want its something like this:
The Hour(TIME TABLE) and then in this hour i want to get all the bottom lines with the minutes (TD INSIDE) for that hour, and then move to next hour (...)
Thans for your time.
[EDIT]
Better log example
Check first table.
TIME TABLE: 05H
TD INSIDE: 15
TD INSIDE: 45
TIME TABLE: 06H
TD INSIDE: 15
TD INSIDE: 35
TD INSIDE: 45
TD INSIDE: 55
TIME TABLE: 07H
TD INSIDE: 05
TD INSIDE: 15
TD INSIDE: 20
TD INSIDE: 25
TD INSIDE: 35
TD INSIDE: 40
TD INSIDE: 50
TD INSIDE: 55
(...)
You can do it:
Element table = document
.select("table.easy-table-creator:nth-child(1) tbody").first();
Elements trAll = table.select("tr");
Elements trAllBody = table.select("tr:not(:first-child)");
// For the Table Hour
Element trFirst = trAll.first();
Elements tds = trFirst.select("td");
for(int i = 0; i < tds.size(); i++){
Element td = tds.get(i);
Log.d("TIME TABLE:", " " + td.text());
String query = "td:nth-child(" + (i + 1) + ")";
Elements subTds = trAllBody.select(query);
for (int j = 0; j < subTds.size(); j++) {
Element subTd = subTds.get(j);
String tdText = subTd.text();
if(!tdText.isEmpty()){
Log.d("TD INSIDE:", " " + subTd.text());
}
}
}
Some interesting points:
your table.easy-table-creator:nth-child(1) tbody selector was selecting all the tables in the page;
with a progressive select you can retrieve all the tds in a given column: td:nth-child(index);
trAllBody here contains all the trs that are not the first one (using the tr:not(:first-child) selector).

Can't retrieve value of a computed cell using JExcelAPI

This is my first post, please bear with me. I'm trying to do something simple: look at the value of a spreadsheet cell that contains a formula. Nothing seems to work, instead of the correct answer (579) , I get "4". (output below). This program creates a simple spreadsheet with numbers in A1 and A2, and the sum in A3.
import java.io.*;
import jxl.*;
import jxl.Workbook;
import jxl.biff.FormulaData;
import jxl.biff.formula.FormulaException;
import jxl.write.Number;
import jxl.write.*;
import jxl.write.Formula;
import jxl.read.biff.CellValue;
public class ReadCell {
public static void main(String[] args) throws IOException,
jxl.read.biff.BiffException,
WriteException, FormulaException
{
String filename = "readcell.xls";
WritableWorkbook workbook = Workbook.createWorkbook(new File(filename));
WritableSheet ws = workbook.createSheet("Sheet1", 0);
Number n = new Number(0,0,123); // 123 in A1
ws.addCell(n);
n = new Number(0,1,456); // 456 in A2
ws.addCell(n);
Formula f = new Formula(0,2, "A1+A2"); // formula in A3, yields 579
ws.addCell(f);
workbook.write();
workbook.close();
//now try to retrieve the sum of A1 + A2, which is in A3 (value should be 579)
Workbook wb = Workbook.getWorkbook( new File (filename));
Sheet sheet = wb.getSheet(0);
Cell cell = sheet.getCell("A3");
System.out.println("\n\nCell A3 contents = " + cell.getContents());
//that didn't work, maybe try it by casting to a NumberCell?
NumberCell numbercell = (NumberCell)cell;
System.out.println("NumberCell value = " + numbercell.getValue());
System.out.println("NumberCell contents = " + numbercell.getContents());
//that didn't work, maybe try it by casting to a FormulaCell?
FormulaCell fc = (FormulaCell)cell;
System.out.println("FormulaCell contents = " + fc.getContents());
System.out.println("FormulaCell formula = " + fc.getFormula());
//that didn't work, maybe try to get contents by casting to FormulaData?
FormulaData fd = (FormulaData)cell;
System.out.println("FormulaData contents = " + fd.getContents());
System.out.println("FormulaData type = " + fd.getType());
//that didn't work, maybe try to get contents by casting to NumberFormulaCell?
NumberFormulaCell nfc = (NumberFormulaCell)cell;
System.out.println("NumberFormulaCell value = " + nfc.getValue());
System.out.println("NumberFormulaCell contents = " + nfc.getContents());
System.out.println("NumberFormulaCell formula = " + nfc.getFormula());
//that didn't work, try to get contents by casting to CellValue?
CellValue cv = (CellValue)cell;
System.out.println("cellValue contents = " + cv.getContents());
//Nothing works and these casts won't compile:
//Number nnn = (Number)cell;
//NumberFormulaRecord nfr = (NumberFormulaRecord)cell;
wb.close();
}
}
Here is the output, the "4"s should be "579"s
Cell A3 contents = 4
NumberCell value = 4.0
NumberCell contents = 4
FormulaCell contents = 4
FormulaCell formula = A1+A2
FormulaData contents = 4
FormulaData type = Numerical Formula
NumberFormulaCell value = 4.0
NumberFormulaCell contents = 4
NumberFormulaCell formula = A1+A2
cellValue contents = 4
Thanks for any help you can provide!
I ran the code that writes the workbook. Then I opened the workbook in Excel. When I told it to close, I was prompted with a message:"Microsoft Excel recalculates formulas when opening files last saved by an earlier version of Excel". After choosing to save, and then running the code that reads (but not the code that writes the workbook) I got the correct cell value of 579. When I deleted the file and ran all the code you posted, I got 4. It looks like the formula needs to be calculated before it can be read. This post seems to say there's no fixing it, and makes a supposition as to why: Updated excel file still returns old values

How to read from mysql and write column wise in csv file?

I have different tables in a database(say mysql). i need to extract some columns from different table and write it in a csv file. consider table 1
A 1
B 2
C 3
table 2 table 3
X 7 AB A1
Y 8 BC B2
Z 10 CD C3
U 11 DE D4
V 12
W 13
i want to write 1st column from table 1,2nd col from table 2, and 1st col from table 3 in a csv file such that empty rows are made null.
output:
A,7,AB
B,8.BC
C,10,CD
null,11,DE
null,12,null
null,13,null
i can do the basic reading and writing from mysql to csv, need help in the logic or code to get the above output. "Looking for a generic solution for say 'n' number of columns from 'n' number of tables". above is jus a example.
I do not know how you read your database but assume you do it with JDBC:
ResultSet tableAReusltSet= null;
ResultSet tableBReusltSet= null;
ResultSet tableCReusltSet= null;
List<PseudeContainer> container = new ArrayList<>();
while (tableAReusltSet.next()) {
PseudeConteiner ps = new PseudoContainer();
ps.col1 = tableAReusltSet.getString("ColumnName");
container.add(ps);
}
int i = 0;
while (tableBReusltSet.next()) {
if(container.size() <= i){
container.add(new PseudeContainer());
}
container.get(i).col2 = tableBReusltSet.getString("ColumnName");
}
i = 0;
while (tableBReusltSet.next()) {
if(container.size() <= i){
container.add(new PseudeContainer());
}
container.get(i).col2 = tableBReusltSet.getString("ColumnName");
}
//.. now you have a collection to work with which you can write
public PseudeContainer {
String col1 = null;
String col2 = null;
String col3 = null;
}
Above should work.. still pseudo code...
Since you just want the logic here is some pseudo code that may help you in whatever language you are using. Since I don't know how you are exporting to csv I made it pretty generic.
arr1 = select column1 from table1;
arr2 = select column2 from table2;
arr3 = select column1 from table3;
max = isBigger(arr1.length, arr2.length);
max = isBigger(max, arr3.length);
for(i=0; i<max; i++)
{
if(arr1[i]=="") arr1[i]=null;
if(arr2[i]=="") arr2[i]=null;
if(arr3[i]=="") arr3[i]=null;
print arr1[i] + "," + arr2[i] + "," + arr3[i];
}
Recommend 3rd party libraries to handle CSV files:
Apache Commons CSV
Open CSV

Categories