Google SpreadSheet Read and Write - java

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

Related

Set an empty in an excel cell using Java (Apache POI 3.10-FINAL)

While iterating through a for each loop I got an empty String. It's giving NullPointerException for this. So, if any empty value is coming then I need to set as empty in Excel too.
I used Cell.CELL_TYPE_BLANK) but it's not working.
Here is the code:
int rowIdx = 0;
int coldx=1;
for(String[] columnValues : values) {
coldx++;
for ( String data : columnValues ) {
Row row = sheet.getRow( rowIdx++ );
if(data!="" ){
row.createCell( coldx ).setCellValue( data );
} else
row.createCell( coldx ).setCellValue(Cell.CELL_TYPE_BLANK);
}
Could someone help me with this how to set empty string?

getting all worksheets data using 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());
}
}
}

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();
}
}

Print Simple values Using Excel, ArrayList and Java from different columns Doesn't work If there is no match between Number rows that has values

What I am trying to do is simply print multiple values using for loop and arraylist from multiple columns with the following code
// =========The SpreadSheet=========
File src = new File("J:\\Excel files\\mutiselect.xlsx");
// Load file
FileInputStream fis = new FileInputStream(src);
// Load WB
XSSFWorkbook wb = new XSSFWorkbook(fis);
// Load Sheet
XSSFSheet sh1 = wb.getSheetAt(0);
List<String> values = new ArrayList<String>(); //values from excel will be stored within this array
Iterator<Row> rows = sh1.rowIterator();
while (rows.hasNext())
{
Row row = rows.next();
if (row.getRowNum() > 0)
{
values.add(row.getCell(1).getStringCellValue());
}
}
System.out.println(values);
Thread.sleep(2000);
List<String> values2 = new ArrayList<String>(); //values from excel will be stored within this array
Iterator<Row> rows2 = sh1.rowIterator();
while (rows2.hasNext())
{
Row row2 = rows2.next();
if (row2.getRowNum() > 0)
{
values2.add(row2.getCell(2).getStringCellValue());
}
}
System.out.println(values2);
fis.close();
driver.quit();
Everything works fine it there is matching number of records within excel on Column B and Column C.
But the problem occurs and it doesn't print from one of the columns or from both columns when there is no match between the number of rows that has values means if there is more value on column B than Column C, or More value on Column C than B it will not print.
Please refer to this image for illustration:
http://i.imgur.com/DO8anzu.png
If the excel is like this the values from one of the columns doesnt get printed or from both columns nothing get printed
and gives me error like this
Exception in thread "main" java.lang.NullPointerException
at one.MultiSelectWithForLoop.main(MultiSelectWithForLoop.java:57)
Line#57 refers to this code
values.add(row.getCell(1).getStringCellValue());
or gives me this error
Exception in thread "main" java.lang.NullPointerException
at one.MultiSelectWithForLoop.main(MultiSelectWithForLoop.java:99)
line#99 refers to this code
values2.add(row2.getCell(2).getStringCellValue());
What I want to do is print out all the values from each column individually even even if there is no match in number of values or its less or more in one column than the other
to do this where do I change in the code please?
P.S this code is being used for Selenium Webdriver with Java
From getCell() documentation
If you ask for a cell that is not defined....you get a null.
When the number of values is different in each column the Iterator still has next line so rows.hasNext() is true, but the cell is empty so row.getCell(1) is null.
When you try to get getStringCellValue() from the null cell you get NullPointerException.
Change
if (row.getRowNum() > 0)
To
if (row.getRowNum() > 0 && row.getCell(1) != null)
What about checking for null before adding to the values and values2 lists?
if(row.getCell(1) != null) {
values.add(row.getCell(1).getStringCellValue());
}
and
if(row2.getCell(2) != null) {
values.add(values2.getCell(2).getStringCellValue());
}

How to hide the following Un-used rows in Excel sheet using Java Apache POI?

I am populating a template Excel sheet, with the data from the database :
for (Map<String, Object> resultRow : dbResults) {
if ((currentRow = sheet.getRow(currentDataRow)) == null) {
currentRow = sheet.createRow(currentDataRow); // Creates a new row.
}
//currentRow.getRowStyle().setHidden(false);
for (int i = 0; i < resultColumns; i++) {
currentCell = currentRow.getCell(i, Row.CREATE_NULL_AS_BLANK);
setCellValue(currentCell, resultRow.get(dbcolumnNames[i]));
}
currentDataRow += 1;
}
// How to hide all empty/Un-used rows following currentDataRow ?
Aim to Achieve :
I want that the Un-Used rows following the populated rows should be hidden ?
All Populated rows must be visible.
Eg: If 1st 100 data rows are filled, then rows following 101 and onward should be hidden.
Please, help !!
Row r = sheet.getRow(indexRow);
if ( r!=null ) {
r.setZeroHeight(true);
}
POI recognizes the number of logical rows in your sheet when you create it.
So as you populate it with 100 rows, it will create 100 records. The rest will appear when you open the XLS in Excel with the default layout - but these are not POI records.
You'll have to create some dummy rows after your last data record like this
for (int i=currentDataRow ;i<65000;i++)
sheet.createRow(i);
Create a cell style, and set it to hidden
CellStyle hiddenstyle = workBook.createCellStyle();
hiddenstyle.setHidden(true);
Set this style for all rows from your last row to end of sheet
while (rows.hasNext()){
Row row1 = rows.next ();
row1.setRowStyle(hiddenstyle);
}
row.setRowStye() and row.getRowStye() are present in poi-3.8-beta4.

Categories

Resources