Write Data into Excel with Cucumber & Groovy

I am writing the data into excel and developing the groovy script with cucumber. I am unable to use all the code at once place to open the file, write data and close the same. If I divide them into functions, I am getting object errors. How to resolve this issue to proceed further ?

Below is the code for reference…
Variables Declaration
public int countrun
public Workbook workbook
public FileInputStream file
public FileOutputStream outFile
public Sheet sheet1
public Row row1
public Cell cell1

@And(“testing the running file indicator (.*)”)
def test_running_file_indicator(String findc) {
if (findc==‘S’) {
file = new FileInputStream ( new File(“D:\Test5.xlsx”)) → Execute only once
workbook = WorkbookFactory. create (file)
sheet1 = workbook.getSheet(‘Sheet1’)
row1 = sheet1.createRow(countrun+1)
cell1 = row1.createCell(countrun+1)

@And(“User enters the (.) in the password (.)”)
def User_enters_the_in_the_password(String pwd5, String ftemp2) {
if (runIndicator!=‘N’) {
WebUI.setText ( findTestObject (‘Object Repository/ORTC01/Page_ATT Security Server Login/input_Password_password’), pwd5, FailureHandling.STOP_ON_FAILURE )

if(ftemp2==‘C’) {
cell1 = row1.createCell(countrun+1) → Write data into excel - runs based number of iterations

@And(“closing the excel file successfully (.*)”) → At the end of execution
def close_excel_file_success(String findc) {
if (findc==‘E’)
outFile = newFileOutputStream( new File(“D:\Test5.xlsx”))