How do I retrieve a specific range using Google Sheets API - android-studio

I have the following code using the Google sheets API and got it working perfectly. It sees all my data and puts it into the app perfectly via the for loop. It runs through the spreadsheets and puts the data in an edit view.
private List<String> getDataFromApi() throws IOException {
String spreadsheetId = "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms";
String range = "Class Data!A2:E";
List<String> results = new ArrayList<String>();
ValueRange response = this.mService.spreadsheets().values()
.get(spreadsheetId, range)
.execute();
List<List<Object>> values = response.getValues();
if (values != null) {
results.add("Name, Major");
for (List row : values) {
results.add(row.get(0) + ", " + row.get(4));
}
}
return results;
}
As you can see, the for loop retrieves the data one by one until there is no more data inside a specific range in the spreadsheet.
My question: I want to retrieve a specific range, not using a for loop. However, as an example, if I want to get cell A1, and I do result.add(A.get(0)), it doesn't work.
How can I retrieve a specific range within the spreadsheet.

Related

Selenium datadriven testing - unable to fetch the data from the Numbers application (macOS)

I am trying to fetch the data from the Numbers application in macOS, In below code is not able to fetch the value from the cell.
public class Excel {
public static String getdata(String sheetname, int rowvalue, int cellvalue)
{
String value = "";
try {
FileInputStream fis = new FileInputStream("./Excel/Logincred.xlsx");
Workbook wb = WorkbookFactory.create(fis);
Sheet sh = wb.getSheet(sheetname);
Row r = sh.getRow(rowvalue);
Cell c = r.getCell(cellvalue);
value = c.toString();
}
catch(Exception e)
{
}
return value;
}
}
You need to append ' before each number in your excel sheet and then your code would work completely fine.
So lets say, you have a value 4 in your excel, you need to change it to '4 and then your read from excel would work

How to make row dynamic in Data Driven Framework

I am working on a Data Driven Project where my test data is from an excel sheet. Am able to fetch data from sheet, but I need to pass only the column value but not Row value in step defn method, so that my test case can complete one set of testing with one row and move to next row.
My code:
public static int getCellData() throws Exception{
int rowData=0;
int NumOfRows=0;
try{
NumOfRows = ExcelWSheet.getPhysicalNumberOfRows();
for(int i=2;i<NumOfRows;i++){
rowData = ExcelWSheet.getRow(i).getPhysicalNumberOfCells();}
}
catch (Exception e){}
return rowData;
}

Paste into Excel locked cells

I'm creating a template for users to input data into. All I want them to be able to do is copy their data from their source and put it into Cells A21-D21. Once pasted they cannot delete or alter anything, excel is used only to be able to print. Repasting is fine as this will be a template. Ideally, users would export directly into this protected worksheet and be done with it, but instrument software just calls for excel not a specific database location.
In short, users get data from an instrument and it is saved in a format that it cannot be manipulated but neither can it be shown on any computer except what's connected to the instrument. I need this data to be put into excel but cannot be altered. Auditors can compare the Raw data to the excel if they choose.
Is there a way to have worksheet protected and select the one unlocked cell(Format Cell), A1, and then have the entire range of A21-D21 filled/pasted into?
The thinking is that people will manipulate the raw data to get the answers they want but this will limit users to paste only.
So I guess, simply, I'm hoping to find a way to allow users to copy/paste and THAT'S IT! ?
I don't know if there is a way to do what you want inside Excel, but it can be done programatically.
// Note: need to add reference to Microsoft.Office.Interop.Excel to get these namespaces
// In Visual Studio, choose Project > Add Reference > COM > Type Libraries >
// Microsoft Excel 16.0 Object Library
using Microsoft.Office.Interop.Excel;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
string fileName = #"c:\users\eric.sundquist\desktop\book1.xlsx";
int worksheetNumber = 1;
List<string> contents = new List<string> { "1", "2", "3", "4" };
PasteIntoProtectedSheet(fileName, worksheetNumber, contents);
}
static void PasteIntoProtectedSheet(string fileName, int worksheetNumber,
List<string> contents)
{
Application excel = new Application();
Workbook workbook = excel.Workbooks.Open(fileName);
workbook.Sheets[worksheetNumber].Unprotect();
// Can pass in password as parameter if needed
Range range = workbook.Sheets[1].Range("A21:D21");
for (int column = 0; column < contents.Count; column++)
{
range.Cells[1, column + 1] = contents[column];
}
workbook.Sheets[worksheetNumber].Protect();
workbook.Save();
workbook.Close();
Marshal.ReleaseComObject(range);
Marshal.ReleaseComObject(workbook);
Marshal.ReleaseComObject(excel);
}
}
}

Input/Export data through MS Excel into OATS Scripts

When trying to get the Input the data from the Excel Sheet while working with OATS tool, it always gets into the catch block of the function. The below is the script written. Please help us resolve this issue.
public String getInputfromExcel(int argColumnNumber,int argRowNumber)throws Exception
{
String inputExcelName = dataPath+".xlsx";
String cellContent = "12";
try
{
Workbook workbook = Workbook.getWorkbook(new File(inputExcelName));
Sheet sheet = workbook.getSheet(0);
Cell a1 = sheet.getCell(argColumnNumber, argRowNumber);
cellContent = (a1.getContents()).toString();
System.out.println(cellContent.toString());
workbook.close();
}
catch (Exception e)
{
addReport("Getting Input From Excel", "Fail","Exception while reading value from excel sheet");
}
return cellContent;
}
Axel has brought up the point. On a further note, if I remember correctly, the function sheet.getCell(arg1, arg2) has first argument as rowNumber and 2nd as columnNumber (both the values are 0 based index).
Its old quetion....but just posting answer it might be helpful for someone needy.
In Oracle Application Testing Suite. NO NEED of external JARs to read/write data.
You can enable DataTable module in the tool
Complete explanation given here, http://www.testinghive.com/how-to-read-write-excel-in-oats/
//Define Sheet name to be read, and provide comma seperated to read multiple sheets
String sheetName = "Sheet1";
//Mention excel sheet path
String strFile= "C:\\Demo\\test.xls";
//Defined array list to add Sheets to read
List sheetList = new ArrayList();
sheetList.add(sheetName);
// Iports Sheet1
datatable.importSheets(strFile, sheetList, true, true);
//get rowcount
info("Total rows :"+datatable.getRowCount());
int rowcount=datatable.getRowCount();
//Loop to read all rows
for (int i=0;i<rowcount;i++)
{
//Set current row fromw here you need to start reading, in this case start from first row
datatable.setCurrentRow(sheetName, i);
String strCompany=(String) datatable.getValue(sheetName,i,"Company");
String strEmpFName=(String) datatable.getValue(sheetName,i,"FirstName");
String strEmpLName=(String) datatable.getValue(sheetName,i,"LastName");
String strEmpID=(String) datatable.getValue(sheetName,i,"EmpID");
String strLocation=(String) datatable.getValue(sheetName,i,"Location");
//prints first name and last name
System.out.println("First Name : "+strEmpFName+", Last Name : "+strEmpLName);
//Sets ACTIVE column in excel sheet to Y
String strActive="Y";
datatable.setValue(sheetName, i, datatable.getColumn(sheetName, datatable.getColumnIndex("Active")), strActive);
}
//Updates sheet with updated values ie ACTIVE column sets to Y
datatable.exportToExcel("C:\\Demo\\test1.xlsx");

apache poi how to disable external reference or external links?

I've been looking on the web for 30 minutes now and can't find any explanation about that. Here is my problem :
I wrote an application with poi to parse some data from 200 excel files or so and put some of it into a new file. I do some cell evaluation with FormulaEvaluator to know the content of the cells before choosing to keep them or not.
Now, when i test it on a test file with only values in the cells, the program works perfectly but when i use it on my pile of files I get this error :
"could not resolve external workbook name"
Is there any way to ignore external workbook references or set up the environment so that it wont evaluate formula with external references?
Because the ones I need don't contain references...
Thank you
Can you not just catch the error, and skip over that cell?
You're getting the error because you've asked POI to evaluate a the formula in a cell, and that formula refers to a different file. However, you've not told POI where to find the file that's referenced, so it objects.
If you don't care about cells with external references, just catch the exception and move on to the next cell.
If you do care, you'll need to tell POI where to find your files. You do this with the setupEnvironment(String[],Evaluator[]) method - pass it an array of workbook names, and a matching array of evaluators for those workbooks.
In order for POI to be able to evaluate external references, it needs access to the workbooks in question. As these don't necessarily have the same names on your system as in the workbook, you need to give POI a map of external references to open workbooks, through the setupReferencedWorkbooks(java.util.Map<java.lang.String,FormulaEvaluator> workbooks) method.
I have done please see below code that is working fine at my side
public static void writeWithExternalReference(String cellContent, boolean isRowUpdate, boolean isFormula)
{
try
{
File yourFile = new File("E:\\Book1.xlsx");
yourFile.createNewFile();
FileInputStream myxls = null;
myxls = new FileInputStream(yourFile);
XSSFWorkbook workbook = new XSSFWorkbook(myxls);
FormulaEvaluator mainWorkbookEvaluator = workbook.getCreationHelper().createFormulaEvaluator();
XSSFWorkbook workbook1 = new XSSFWorkbook(new File("E:\\elk\\lookup.xlsx"));
// Track the workbook references
Map<String,FormulaEvaluator> workbooks = new HashMap<String, FormulaEvaluator>();
workbooks.put("Book1.xlsx", mainWorkbookEvaluator);
workbooks.put("elk/lookup.xlsx", workbook1.getCreationHelper().createFormulaEvaluator());
workbook2.getCreationHelper().createFormulaEvaluator());
// Attach them
mainWorkbookEvaluator.setupReferencedWorkbooks(workbooks);
XSSFSheet worksheet = workbook.getSheetAt(0);
XSSFRow row = null;
if (isRowUpdate) {
int lastRow = worksheet.getLastRowNum();
row = worksheet.createRow(++lastRow);
}
else {
row = worksheet.getRow(worksheet.getLastRowNum());
}
if (!isFormula) {
Cell cell = row.createCell(row.getLastCellNum()==-1 ? 0 : row.getLastCellNum());
cell.setCellValue(Double.parseDouble(cellContent));
} else {
XSSFCell cell = row.createCell(row.getLastCellNum()==-1 ? 0 : row.getLastCellNum());
System.out.println(cellContent);
cell.setCellFormula(cellContent);
mainWorkbookEvaluator.evaluateInCell(cell);
cell.setCellFormula(cellContent);
// mainWorkbookEvaluator.evaluateInCell(cell);
//System.out.println(cell.getCellFormula() + " = "+cell.getStringCellValue());
}
workbook1.close();
myxls.close();
FileOutputStream output_file =new FileOutputStream(yourFile,false);
//write changes
workbook.write(output_file);
output_file.close();
} catch (Exception e) {
e.printStackTrace();
}
}

Resources