package com.mugil.first import jxl.* import jxl.write.* class ExcelUtils { public static void main(String[] args) { writeExcel() readExcel() } static def writeExcel() { WritableWorkbook workbook = Workbook.createWorkbook(new File("d:\\output.xls")) WritableSheet sheet = workbook.createSheet("Worksheet1", 0) for(int i=0;i<3;i++) { for(int j=0;j<5;j++) { Label label = new Label(i, j, i+","+j); sheet.addCell(label); } } workbook.write() workbook.close() } static def readExcel() { Workbook workbook1 = Workbook.getWorkbook(new File("d:\\output.xls")) Sheet sheet1 = workbook1.getSheet(0) Cell a1 = sheet1.getCell(0,2) Cell b2 = sheet1.getCell(2,2) Cell c2 = sheet1.getCell(2,1) println a1.getContents(); println b2.getContents(); println c2.getContents(); workbook1.close() } }
Daily Archives: February 8, 2017
Groovy Few Basics
What def Keyword Does?
def is a replacement for a type name. In variable definitions it is used to indicate that you don’t care about the type. In variable definitions it is mandatory to either provide a type name explicitly or to use “def” in replacement. This is needed to make variable definitions detectable for the Groovy parser.You can think of def as an alias of Object and you will understand it in an instant.
def name = "Stephanie" println name.toUpperCase() // no cast required
while you would need an explicit cast in the Java version
Object name = "Stephanie"; System.out.println(((String) name).toUpperCase());
Omitting the “def” keyword puts the variable in the bindings for the current script and groovy treats it (mostly) like a globally scoped variable:
x = 1 assert x == 1 assert this.binding.getVariable("x") == 1
Using the def keyword instead does not put the variable in the scripts bindings:
def y = 2 assert y == 2 try { this.binding.getVariable("y") } catch (groovy.lang.MissingPropertyException e) { println "error caught" }
Prints: “error caught”
If you define a method in your script, it won’t have access to the variables that are created with “def” in the body of the main script as they aren’t in scope:
x = 1 def y = 2 public bar() { assert x == 1 try { assert y == 2 } catch (groovy.lang.MissingPropertyException e) { println "error caught" } } bar()
prints “error caught”
The “y” variable isn’t in scope inside the function. “x” is in scope as groovy will check the bindings of the current script for the variable.