getting all worksheets data using java - java

I have a google spreadsheet which contains 2 or more worksheets. I am able to print all tabs name or worksheets name using java. I'm looking for a way to print all worksheet data by default it prints only first tab or worksheet. I am attaching my code below plz someone helps me I am pretty new to this code snippet

You need to specify the range first, then return the data in a ValueRange object. See example code below
String range = "UK!A2:E";
ValueRange response = service.spreadsheets().values()
.get(spreadsheetId, range)
.execute();
List<List<Object>> values = response.getValues();
if (values == null || values.isEmpty()) {
System.out.println("No data found.");
} else {
for (List row : values) {
Iterator<Object> elem = row.iterator();
while (elem.hasNext()) {
System.out.println(elem.next());
}
}
}

Related

Google SpreadSheet Read and Write

I had coded to take input from excel sheet and write to excel sheet PASS or Fail.
I am using Apache POI to get this done.
Here is sample code for same :
for (int row=1 ;row<=5;row++)
{
//This will second cell value in first row.
System.out.println(sheet.getRow(row).getCell(2).getStringCellValue());
//This will set value pass on 4th cell of first row.
sheet.getRow(row).createCell(4).setCellValue("Pass");
}
Now I am want to attain same using google spreadsheet , I am able to read and write from sheet , but not able to apply this as I had done using APACHE POI ,
Just for quick ref :
To Read Data from spread Sheet
ValueRange response = service.spreadsheets().values()
.get(spreadsheetId, range)
.execute();
List<List<Object>> values = response.getValues();
if (values == null || values.size() == 0) {
System.out.println("No data found.");
} else {
for (List row : values) {
// Print columns A and E, which correspond to indices 0 and 4.
System.out.println(row.get(0));
}
}
And To Write :
List<List<Object>> values1 = Arrays.asList(
Arrays.asList("PASS")
// Additional rows ...
);
ValueRange body = new ValueRange()
.setValues(values1);
UpdateValuesResponse result =
service.spreadsheets().values().update(spreadsheetId, range, body)
.setValueInputOption("RAW")
.execute();
System.out.printf("%d cells updated.", result.getUpdatedCells());
Can some one please suggest how to attain same working as I had done using Apache POI
Thanks

Put different values in a map and write to excel using POI using selenium

I want to put different values in a map and write them in an excel file using POI libraries. I have two questions and it would be great if someone can answer them
1) I want to put different values at different stages in a map and write them in different columns of the excel. for eg. at page 1, I have a value A which I want to put in the map and at page 2, I have a value B and C which I want to put into the map. I want to write these values in excel at different columns.
2) I may be visiting page 1 and 2 again and at that time I would want these values A and B to be written in a new ROW. How can I increment the row and write these values in a new Row everytime, I visit page 1 and 2 again.
I have written something like,
Map<String, Object[]> putdatainMap;
String orderid=driver.findElement(By.id("ORDER_ID")).getAttribute("value");
putdatainMap.put(orderid, ?)//This I get from page1
String txnid=driver.findElement(By.name("TXN_ID").getAttribute("value");
putdatainMap.put(txnid,?)//I don't want to lose the orderid which I got earlier, rather I want to put the orderid and txnid in different columns)
String status=driver.findElement(By.id("status").getAttribute("value");
putdatainMap.put(status,?)//The txn id and status I get from page2
Now I want to write the above values in an excel file and do something, that when I restart this flow the new values should come in a new Row.
Set <String> keyset = putdatainMap.keySet();
int rownum = 0;
for (String key : keyset)
{
Row row = sheet.createRow(rownum++);
Object [] objArr = data.get(key);
int cellnum = 0;
for (Object obj : objArr)
{
Cell cell = row.createCell(cellnum++);
if(obj instanceof String)
cell.setCellValue((String)obj);
else if(obj instanceof Integer)
cell.setCellValue((Integer)obj);
}
}
try
{
FileOutputStream out = new FileOutputStream(new File(filepath +"/"+filename+".xlsx"));
workbook.write(out);
out.close();
System.out.println("Data written to drive sucessfully");
}
catch (Exception e)
{
e.printStackTrace();
}
}

Java - Parse delimited file and find column datatypes

Is it possible to parse a delimited file and find column datatypes? e.g
Delimited file:
Email,FirstName,DOB,Age,CreateDate
test#test1.com,Test User1,20/01/2001,24,23/02/2015 14:06:45
test#test2.com,Test User2,14/02/2001,24,23/02/2015 14:06:45
test#test3.com,Test User3,15/01/2001,24,23/02/2015 14:06:45
test#test4.com,Test User4,23/05/2001,24,23/02/2015 14:06:45
Output:
Email datatype: email
FirstName datatype: Text
DOB datatype: date
Age datatype: int
CreateDate datatype: Timestamp
The purpose of this is to read a delimited file and construct a table creation query on the fly and insert data into that table.
I tried using apache validator, I believe we need to parse the complete file in order to determine each column data type.
EDIT: The code that I've tried:
CSVReader csvReader = new CSVReader(new FileReader(fileName),',');
String[] row = null;
int[] colLength=(int[]) null;
int colCount = 0;
String[] colDataType = null;
String[] colHeaders = null;
String[] header = csvReader.readNext();
if (header != null) {
colCount = header.length;
}
colLength = new int[colCount];
colDataType = new String[colCount];
colHeaders = new String[colCount];
for (int i=0;i<colCount;i++){
colHeaders[i]=header[i];
}
int templength=0;
String tempType = null;
IntegerValidator intValidator = new IntegerValidator();
DateValidator dateValidator = new DateValidator();
TimeValidator timeValidator = new TimeValidator();
while((row = csvReader.readNext()) != null) {
for(int i=0;i<colCount;i++) {
templength = row[i].length();
colLength[i] = templength > colLength[i] ? templength : colLength[i];
if(colHeaders[i].equalsIgnoreCase("email")){
logger.info("Col "+i+" is Email");
} else if(intValidator.isValid(row[i])){
tempType="Integer";
logger.info("Col "+i+" is Integer");
} else if(timeValidator.isValid(row[i])){
tempType="Time";
logger.info("Col "+i+" is Time");
} else if(dateValidator.isValid(row[i])){
tempType="Date";
logger.info("Col "+i+" is Date");
} else {
tempType="Text";
logger.info("Col "+i+" is Text");
}
logger.info(row[i].length()+"");
}
Not sure if this is the best way of doing this, any pointers in the right direction would be of help
If you wish to write this yourself rather than use a third party library then probably the easiest mechanism is to define a regular expression for each data type and then check if all fields satisfy it. Here's some sample code to get you started (using Java 8).
public enum DataType {
DATETIME("dd/dd/dddd dd:dd:dd"),
DATE("dd/dd/dddd",
EMAIL("\\w+#\\w+"),
TEXT(".*");
private final Predicate<String> tester;
DateType(String regexp) {
tester = Pattern.compile(regexp).asPredicate();
}
public static Optional<DataType> getTypeOfField(String[] fieldValues) {
return Arrays.stream(values())
.filter(dt -> Arrays.stream(fieldValues).allMatch(dt.tester)
.findFirst();
}
}
Note that this relies on the order of the enum values (e.g. testing for datetime before date).
Yes it is possible and you do have to parse the entire file first. Have a set of rules for each data type. Iterate over every row in the column. Start of with every column having every data type and cancel of data types if a row in that column violates a rule of that data type. After iterating the column check what data type is left for the column. Eg. Lets say we have two data types integer and text... rules for integer... well it must only contain numbers 0-9 and may begin with '-'. Text can be anything.
Our column:
345
-1ab
123
The integer data type would be removed by the second row so it would be text. If row two was just -1 then you would be left with integer and text so it would be integer because text would never be removed as our rule says text can be anything... you dont have to check for text basically if you left with no other data type the answer is text. Hope this answers your question
I have slight similar kind of logic needed for my project. Searched lot but did not get right solution. For me i need to pass string object to the method that should return datatype of the obj. finally i found post from #sprinter, it looks similar to my logic but i need to pass string instead of string array.
Modified the code for my need and posted below.
public enum DataType {
DATE("dd/dd/dddd"),
EMAIL("#gmail"),
NUMBER("[0-9]+"),
STRING("^[A-Za-z0-9? ,_-]+$");
private final String regEx;
public String getRegEx() {
return regEx;
}
DataType(String regEx) {
this.regEx = regEx;
}
public static Optional<DataType> getTypeOfField(String str) {
return Arrays.stream(DataType.values())
.filter(dt -> {
return Pattern.compile(dt.getRegEx()).matcher(str).matches();
})
.findFirst();
}
}
For example:
Optional<DataType> dataType = getTypeOfField("Bharathiraja");
System.out.println(dataType);
System.out.println(dataType .get());
Output:
Optional[STRING]
STRING
Please note, regular exp pattern is vary based on requirements, so modify the pattern as per your need don't take as it is.
Happy Coding !

Batching in Java and Excel gives different results

I need to batch elements that have similar client id (String type, but at the moment only numeric values, like "12345", "235134", etc.)
Map<String, List<Client>> _batched = new HashMap<String, List<Client>>();
for (Client c : _Clients)
{
String id = c.getIdClient();
List<Client> clients = _batched.get(id);
if(_clients == null){
clients = new ArrayList<Client>();
_batched.put(id, clients);
}
clients.add(c);
}
The problem is that when I compare this function with the results of Excel (=SUM(IF(FREQUENCY(C2:C618,C2:C618)>0,1))), then I get different results, i.e. 526 and 519.
Is something wrong with my code?
Your problem is here:
String id = c.getIdClient();
List<Client> _clients = _batched.get(id);
if(_clients == null){
pois = new ArrayList<Client>();
_batched.put(id, _clients);
}
_clients.add(c);
You create a new array into a variable called pois but then put the contents of the variable _clients into _batched. What happens with the value put into pois?
I don't understand how that doesn't null pointer exception actually.

Google Spreadsheet API - find the first empty cell in a column?

Is there a good way to get the first empty cell in a column from Google's spreadsheet service via Java?
I know I can use:
public CellFeed CheckColumn(int row, int col)
throws IOException, ServiceException {
CellQuery query = new CellQuery(cellFeedUrl);
query.setMinimumRow(row);
query.setMaximumRow(row);
query.setMinimumCol(col);
query.setMaximumCol(col);
query.setReturnEmpty(true);
CellFeed feed = service.query(query, CellFeed.class);
int cell_loc[];
for (CellEntry entry : feed.getEntries()) {
cell_loc=CheckIfEmpty(entry);
}
return cell_loc;
}
And walk through the entries, but I'd rather not load the entire column at once, it's slow for my users and it seems bad to just walkthrough the entire column
Any thoughts?
This small snippet will create a function in Google Spreadsheet with Google Apps Script:
function emptySpace(array) {
// set counter
var counter = 0;
// itterate through values
for (i in array){
if (array[i].length > 1) {
throw ("Only single column of data");
} else {
if(array[i][0] != "") {
counter++;
} else {
break;
}
}
}
// return value + 1
return counter + 1;
}
Add this script, via the script editor, to your spreadsheet and the function emptySpace is available throughout the worksheet, like so: =emptySpace(A1:A7).
See example file I've created: empty space

Categories

Resources