I am trying to write some data into a xlsx file using apache poi.
and my code goes like this
The excel sheet contains 6 rows and 2 columns already
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class excelwrite {
public void excelWrite(String filepath, String filename, String
sheetname, String[] dataTowrite) throws IOException
{
File file = new File(filepath+"\\"+filename);
FileInputStream inputstream = new FileInputStream(file);
Workbook workbook = null;
String fileextensionname =
filename.substring(filename.indexOf(".")+1);
if(fileextensionname.equalsIgnoreCase("xlsx"))
workbook = new XSSFWorkbook(inputstream);
else
workbook = new HSSFWorkbook(inputstream);
Sheet sheet = workbook.getSheet(sheetname);
int Rowcount = sheet.getFirstRowNum() - sheet.getLastRowNum();
Row row = sheet.getRow(0);
Row newrow = sheet.createRow(Rowcount+1);
for(int i=0;i<row.getLastCellNum();i++)
{
Cell cell = newrow.createCell(i);
cell.setCellValue(dataTowrite[i]);
}
inputstream.close();
FileOutputStream outputstream = new FileOutputStream(file);
workbook.write(outputstream);
outputstream.close();
}
public static void main(String[] args) throws IOException {
excelwrite write = new excelwrite();
String[] datatowrite = {"Mr. E","DURGAPUR"};
String filepath = "C:\\Users\\malfoy\\Desktop";
write.excelWrite(filepath,"testfile.xlsx","read",datatowrite);
}
}
Now while running the program, there is an exception which says
"Invalid row number (-4) outside allowable range (0..1048575)".
How to fix this?
int Rowcount = sheet.getLastRowNum() - sheet.getFirstRowNum();
Related
I'm using a pre-filled Excel range to overwrite it with editpyxl. I saw that openpyxl and xlsxwriter are not able (yet) to keep shapes etc. in other sheets when another sheet is written.
And editpyxl takes a lot of time to write to the Excel range. However, it also blocks the application so I'm trying to make it asynchronous, but wasn't able yet as using await doesn't just work out of the box like magic..
from fastapi import FastAPI, Request
from fastapi.responses import FileResponse
import editpyxl
app = FastAPI()
temp_folder = "./_temp"
file_output_name = "output_fileresponse.xlsx"
#app.get("/my-projects/{project}/download-report", include_in_schema=False)
async def my_project(request: Request,
project: str, ):
report_template = Path(path, excel_file)
wb = editpyxl.Workbook()
wb.open(report_template)
ws = wb.active
def write_pd_to_xlsx(xlsx_range, pd_series):
ss = ws.cells_in_range(xlsx_range)
sc = df[pd_series]
zipped_lists = zip(ss, sc)
for xlsx_cell, pd_value in zipped_lists:
ws.cell(xlsx_cell).value = pd_value
total_records = 2000
ranges_excel_file = [f"C8:C{total_records + 7}", f"D8:D{total_records + 7}",
f"E8:E{total_records + 7}", f"F8:F{total_records + 7}",]
columns_to_use = ["Column 1", "Column 2", "Column 3", "Column 4"]
zipped_ranges_columns = zip(ranges_excel_file, columns_to_use)
for rng, col in zipped_ranges_columns:
write_pd_to_xlsx(rng, col)
wb.save(os.path.join(temp_folder, file_output_name))
response = FileResponse(os.path.join(temp_folder, file_output_name), filename=file_output_name)
wb.close()
return response
I want to create a groovy script that will generate two scenarios of a mapping that have two physical layers.
I have the code below, but it seems that it's not correct. I try to pass as value for "generateSecnario" method, the physical layer. Don't know if it's ok.
import oracle.odi.domain.project.finder.IOdiProjectFinder;
import oracle.odi.domain.model.finder.IOdiDataStoreFinder;
import oracle.odi.domain.project.finder.IOdiFolderFinder;
import oracle.odi.domain.mapping.finder.IMappingFinder;
import oracle.odi.domain.model.OdiDataStore;
import oracle.odi.domain.model.OdiModel;
import oracle.odi.domain.model.finder.IOdiModelFinder;
import oracle.odi.core.persistence.transaction.support.DefaultTransactionDefinition;
import oracle.odi.generation.support.OdiScenarioGeneratorImpl;
import oracle.odi.generation.IOdiScenarioGenerator;
import oracle.odi.domain.runtime.scenario.OdiScenario;
import oracle.odi.domain.mapping.Mapping;
import oracle.odi.domain.mapping.finder.IMappingFinder;
import oracle.odi.domain.runtime.scenario.finder.IOdiScenarioFinder;
import oracle.odi.domain.project.OdiProject;
txnDef = new DefaultTransactionDefinition()
tm = odiInstance.getTransactionManager()
tme = odiInstance.getTransactionalEntityManager()
txnStatus = tm.getTransaction(txnDef)
def fm = ((IMappingFinder) tme.getFinder(Mapping.class)) // shorcut to Find Mapping
def mappingList = fm.findAll().findAll {w-> w.getProject().getCode() == 'DL_GENERATE_MAPPINGS'
}
if (mappingList == null) {
println "Map is null"
}
ms = mappingList.iterator()
while (ms.hasNext()) {
ms_i = ms.next()
println ms_i.getName()
scenName = ms_i.getName();
stxnDef = new DefaultTransactionDefinition()
stm = odiInstance.getTransactionManager()
stme = odiInstance.getTransactionalEntityManager()
stxnStatus = stm.getTransaction(stxnDef)
OdiScenario sc = ((IOdiScenarioFinder) stme.getFinder(OdiScenario.class)).findLatestByName(scenName)
if (sc != null) {
println "Scenario already exist"
println sc
}
println("test");
odiInstance.getTransactionalEntityManager().persist(ms_i);
PhysicalDesignList = ms_i.getExistingPhysicalDesigns();
println("ceva" + PhysicalDesignList);
for (pd in PhysicalDesignList) {
if (pd.getName() == "DailyLayer") {
println("test1");
IOdiScenarioGenerator gene = new OdiScenarioGeneratorImpl(odiInstance);
OdiScenario newScen = gene.generateScenario(ms_i, scenName, "100");
} else if (pd.getName() == "CorrectionLayer") {
println("test2");
IOdiScenarioGenerator gene = new OdiScenarioGeneratorImpl(odiInstance);
OdiScenario newScen = gene.generateScenario(ms_i, scenName, "200");
}
}
println newScen
//tme.persist(newScen)
stm.commit(stxnStatus)
println "Created"
//odiInstance.close()
}
tm.commit(txnStatus)
Do you know how to do this ?
Thank you,
UPDATE 1
If I change "ms_i" in generateScenario method with "pd" (generating scenario for each physical layer instead of each mapping), I god this error:
Hi, I forgot to mention that I already replaced with pd and tried. When I run this first, I got this error:
No such property: newScen for class: Generate_scenarios_v1 (Subtract
18 from the error line number to account for the standard imports)
groovy.lang.MissingPropertyException: No such property: newScen for
class: Generate_scenarios_v1 at
org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:53)
at
org.codehaus.groovy.runtime.callsite.PogoGetPropertySite.getProperty(PogoGetPropertySite.java:52)
at
org.codehaus.groovy.runtime.callsite.AbstractCallSite.callGroovyObjectGetProperty(AbstractCallSite.java:307)
at Generate_scenarios_v1.run(Generate_scenarios_v1.groovy:80) at
groovy.lang.GroovyShell.runScriptOrMainOrTestOrRunnable(GroovyShell.java:263)
at groovy.lang.GroovyShell.run(GroovyShell.java:518) at
groovy.lang.GroovyShell.run(GroovyShell.java:497) at
groovy.lang.GroovyShell.run(GroovyShell.java:170) at
oracle.di.studio.groovy.GroovyScriptRunInstance.run(GroovyScriptRunInstance.java:222)
After this, I i'll try to run it again, it goes into loop or something like that .. it doesn't do anything, like it's blocked by something. Maybe I need to close some connection and I don't do it ...
The first parameter of the generateScenario method you are invoking is of type IOdiScenarioSource. One of the implementation of this interface is MapPhysicalDesign, so you could pass that instead of your mapping.
OdiScenario newScen = gene.generateScenario(pd, scenName, "100");
I see you are using the same name for the two scenarii with a different version number. This might lead to some confusion in the long run, especially because executing version -1 of a scenario will take the latest version (so the correction in your case). I would recommend to use 2 different names (e.g. scenName+'_DAILY' and scenName+'_CORR')
I am new to coding, below is a groovy script that I am using in Soap UI to dump response data into an excel sheet. I am getting error at line 55, '}' for closing if condition (which I believe is not the issue). Earlier I was using only jexl and it was working fine but then I switched to poi to be able to append data in same sheet and it throws error. I have already copied all the relevant jars in bin/ext.
import java.io.*;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.*;
import jxl.*;
def grUtils = new com.eviware.soapui.support.GroovyUtils(context)
def ReqHolder = grUtils.getXmlHolder("Search#Response")
def HotelCount = ReqHolder["count(//*:Property)"]
def tCNo = context.expand( '${DSS#TCNo.}' )
if (tCNo =='1')
{
FileInputStream fsIP= new FileInputStream(new File("C:/Users/129858/Desktop/Soap/Simplify_HTE/SearchSink.xls"));
HSSFWorkbook copy = new HSSFWorkbook(fsIP);
HSSFSheet worksheet = copy.getSheetAt(0);
CL = 0;
rows = HotelCount.toInteger();
Cell cell = null;
cell = worksheet.getRow(0).getCell(0);
cell.setCellValue("TCNo.");
cell = worksheet.getRow(0).getCell(1);
cell.setCellValue("HotelName");
cell = worksheet.getRow(0).getCell(2);
cell.setCellValue("HotelCode");
cell = worksheet.getRow(0).getCell(3);
cell.setCellValue("BrandCode");
for( tc_row in 1..rows){
Cell box = null;
cell = worksheet.getRow(tc_row).getCell(CL);
String s0 = tCNo;
cell.setCellValue(s1);
cell = worksheet.getRow(tc_row).getCell(CL+1);
String s1 = ReqHolder.getNodeValue("//*:Property[$tc_row]/#HotelName");
cell.setCellValue(s1);
cell = worksheet.getRow(tc_row).getCell(CL+2);
String s2 = ReqHolder.getNodeValue("//*:Property[$tc_row]/#HotelCode");
cell.setCellValue(s2);
cell = worksheet.getRow(tc_row).getCell(CL+3);
String s3 = ReqHolder.getNodeValue("//*:Property[$tc_row]/#BrandCode");
cell.setCellValue(s3);
}
fsIP.close();
FileOutputStream fsOP =new FileOutputStream(new File("C:/Users/129858/Desktop/Soap/Simplify_HTE/SearchSink.xls");
copy.write(fsOP);
fsOP.close();
}
else{
FileInputStream file = new File("C:/Users/129858/Desktop/Soap/Simplify_HTE/SearchSink.xls");
HSSFWorkbook wb = new HSSFWorkbook(file);
HSSFsheet ws = wb.getSheetAt(0):
datarows = ws.getRows();
col = 0;
log.info datarows
exrows = HotelCount.toInteger() + datarows + 1;
log.info exrows
for( tc_ro in datarows+1..exrows)
{
Cell box = null;
cell = worksheet.getRow(tc_ro).getCell(col);
String s0 = tCNo;
cell.setCellValue(s1);
cell = worksheet.getRow(tc_ro).getCell(col+1);
String s1 = ReqHolder.getNodeValue("//*:Property[$tc_row]/#HotelName");
cell.setCellValue(s1);
cell = worksheet.getRow(tc_ro).getCell(col+2);
String s2 = ReqHolder.getNodeValue("//*:Property[$tc_row]/#HotelCode");
cell.setCellValue(s2);
cell = worksheet.getRow(tc_ro).getCell(col+3);
String s3 = ReqHolder.getNodeValue("//*:Property[$tc_row]/#BrandCode");
cell.setCellValue(s3);
}
fsIP.close();
FileOutputStream fsOP =new FileOutputStream(new File("C:/Users/129858/Desktop/Soap/Simplify_HTE/SearchSink.xls");
copy.write(fsOP);
fsOP.close();
}
In line 53 you are missing one closing bracket:
FileOutputStream fsOP =new FileOutputStream(new File("C:/Users/129858/Desktop/Soap/Simplify_HTE/SearchSink.xls");
It should be:
FileOutputStream fsOP =new FileOutputStream(new File("C:/Users/129858/Desktop/Soap/Simplify_HTE/SearchSink.xls"));
The same thing happens in line 91.
Consider using an editor with code validation and completion. You can choose from wide range of free to use IDE's like IntelliJ IDEA, Eclipse, Netbeans and so on. IDEA for instance would quickly tell you that you are missing this closing bracket and you would save a lot of time.
Thanks Stepniak, for pointing me in the right direction. It had way too many errors and some really crappy codding. Its working fine now.
import java.io.*;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.*;
import jxl.*;
def grUtils = new com.eviware.soapui.support.GroovyUtils(context)
def ReqHolder = grUtils.getXmlHolder("Search#Response")
def HotelCount = ReqHolder["count(//*:Property)"]
def tCNo = context.expand( '${DSS#TCNo.}' )
if (tCNo =='1')
{
HSSFWorkbook copy = new HSSFWorkbook();
HSSFSheet worksheet = copy.createSheet("SearchSink");
CL = 0;
rows = HotelCount.toInteger();
Row head = worksheet.createRow(0);
Cell cell0 = head.createCell(0);
cell0.setCellValue("TCNo.");
Cell cell1 = head.createCell(1);
cell1.setCellValue("HotelName");
Cell cell2 = head.createCell(2);
cell2.setCellValue("HotelCode");
Cell cell3 = head.createCell(3);
cell3.setCellValue("BrandCode");
for( tc_row in 1..rows){
Row data = worksheet.createRow(tc_row);
Cell box0 = data.createCell(CL);
String s0 = tCNo;
box0.setCellValue(s0);
Cell box1 = data.createCell(CL+1);
String s1 = ReqHolder.getNodeValue("//*:Property[$tc_row]/#HotelName");
box1.setCellValue(s1);
Cell box2 = data.createCell(CL+2);
String s2 = ReqHolder.getNodeValue("//*:Property[$tc_row]/#HotelCode");
box2.setCellValue(s2);
Cell box3 = data.createCell(CL+3);
String s3 = ReqHolder.getNodeValue("//*:Property[$tc_row]/#BrandCode");
box3.setCellValue(s3);
}
FileOutputStream fsOP =new FileOutputStream(new
File("C:/Users/129858/Desktop/Soap/Simplify_HTE/SearchSink.xls"));
copy.write(fsOP);
fsOP.close();
}
else{
FileInputStream file = new FileInputStream(new
File("C:/Users/129858/Desktop/Soap/Simplify_HTE/SearchSink.xls"));
HSSFWorkbook wb = new HSSFWorkbook(file);
HSSFSheet ws = wb.getSheetAt(0);
int datarows = ws.getLastRowNum();
col = 0;
log.info datarows
exrows = HotelCount.toInteger() + datarows;
log.info exrows
for( tc_ro in datarows+1..exrows)
{
Row data = ws.createRow(tc_ro);
Cell box0 = data.createCell(col);
String s0 = tCNo;
box0.setCellValue(s0);
Cell box1 = data.createCell(col+1);
String s1 = ReqHolder.getNodeValue("//*:Property[$tc_ro-$datarows]/#HotelName");
box1.setCellValue(s1);
Cell box2 = data.createCell(col+2);
String s2 = ReqHolder.getNodeValue("//*:Property[$tc_ro-$datarows]/#HotelCode");
box2.setCellValue(s2);
Cell box3 = data.createCell(col+3);
String s3 = ReqHolder.getNodeValue("//*:Property[$tc_ro-$datarows]/#BrandCode");
box3.setCellValue(s3);
}
file.close();
FileOutputStream fsOP =new FileOutputStream(new
File("C:/Users/129858/Desktop/Soap/Simplify_HTE/SearchSink.xls"));
wb.write(fsOP);
fsOP.close();
}
I'm trying to have my code search for specific keywords, and based on those specific keywords create a scanner user-input prompt to replace such keywords.
For example, in the txt file:
Hi my name is < name>, What is your name? is your name < name>?
I like to eat < food>. Do you?
The program should detect the "< name>" and prompt the user to enter in a name twice for different keywords.
So far I have this:
// Java program to illustrate reading from Text File
// Using scanner class
import java.io.File;
import java.util.Scanner;
public class TxtOutput{
public static void main(String[] args) throws Exception
{
// pass the path to the file as a parameter
File file = new File("C:\\Users\\aaron\\Documents\\TestTXT\\test.txt");
Scanner sc = new Scanner(file);
//Types of keywords
//<adjective>, <plural-noun>, <place>, <noun>, <funny-noise>, <person's-name>, <job>, <CITY>, , <Color!>
//, <Exciting-adjective>, <Interersting-Adjective>, <aDvErB>, <NUMBER>, <Plural-noun>, <body-part>, <verb>,
//<Number>, <verB>, <job-title>,
String data1 = sc.nextLine();
if (data1.contains("<job>"));
Scanner user_input = new Scanner (System.in);
String job1;
System.out.println("Enter a profession");
job1 = user_input.next();
String replacedData1 = data1.replace("<job>", job1 );
System.out.println(replacedData1);
}
}
The program can only detect one keyword and it has a pre-made if and else statement. Is there a way to make an if and else statement with a scanner based on the keywords such as "< name>" or "< food>" in a line?
I don't want to bombard this program with an unnecessary amount of pre-made if and else statements. I was wondering if there's a more efficient way to do this.
You could search the whole data file for <..> keyword templates using regex, add the keywords found to a unique Set, and then loop over the keywords to ask for replacements. I think you like this:
I suggest specifying the keyword templates explicitly using alternations | in the regex like that:
<adjective>|<plural-noun>|<place>|<noun>|<funny-noise>|<person's-name>|<job>|<CITY>|<Color!>|<Exciting-adjective>|<Interersting-Adjective>|<aDvErB>|<NUMBER>|<Plural-noun>|<body-part>|<verb>|<Number>|<verB>|<job-title>
Demo
We could use a generic regex like <[^<>]+> but I don't know what else is in your file. Give it a try.
Putting everything together, complete sample:
import java.util.*;
import java.lang.*;
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class Ideone {
public static void main(String[] args) throws java.lang.Exception {
Set < String > uniqueKeywords = new HashSet < String > ();
final String regex = "<adjective>|<plural-noun>|<place>|<noun>|<funny-noise>|<person's-name>|<job>|<CITY>|<Color!>|<Exciting-adjective>|<Interersting-Adjective>|<aDvErB>|<NUMBER>|<Plural-noun>|<body-part>|<verb>|<Number>|<verB>|<job-title>";
final String filecontent = "Text template containing all sorts of .. <adjective>, <plural-noun>, <place>, <noun>, <funny-noise>, <person's-name>, <job>, <CITY>, , <Color!> <Exciting-adjective>, <Interersting-Adjective>, <aDvErB>, <NUMBER>, <Plural-noun>, <body-part>, <verb>, <Number>, <verB>, <job-title>, String data1 = sc.nextLine(); blah blah";
final Pattern pattern = Pattern.compile(regex, Pattern.DOTALL);
final Matcher matcher = pattern.matcher(filecontent);
while (matcher.find()) {
uniqueKeywords.add(matcher.group(0));
}
Scanner user_input = new Scanner(System.in);
for (String keyword: uniqueKeywords) {
System.out.println("Enter a " + keyword);
String replacement = user_input.next();
String replacedData1 = filecontent.replace(keyword, replacement);
System.out.println(replacedData1);
}
}
}
I have a requirement to write a results (Pass/Fail) in the same excel sheet where the script reads the parameter in a FOR loop. It is throwing an error:
org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object 'jxl.read.biff.WorkbookParser#3da0525b' with class 'jxl.read.biff.WorkbookParser' to class 'jxl.write.WritableWorkbook' error at line: 16
My code:
import jxl.*;
import jxl.write.*;
import java.io.*;
import groovy.json.JsonSlurper
//Get project path
def groovyUtils = new com.eviware.soapui.support.GroovyUtils(context)
def projectPath = groovyUtils.projectPath
def testCaseName = testRunner.testCase.name
//Read excel file and get the input value
WritableWorkbook xlwb = Workbook.getWorkbook(new File ("${projectPath}\\${testCaseName}.xls"))
Sheet inputxlsh = xlwb.getSheet(0)
inputRowCount = inputxlsh.getRows();
WritableSheet outputxlsh = xlwb.getSheet(1)
outputRowCount = outputxlsh.getRows();
log.info "Executing Test Case " + testCaseName
log.info "Total records to send API request to webservice from the file : " + inputRowCount -1
for (i=0;i<inputRowCount-1;i++)
{
Cell requestParam1 = inputxlsh.getCell(0,i+1)
affkey = requestParam1.getContents()
Cell requestParam2 = inputxlsh.getCell(1,i+1)
etid = requestParam2.getContents()
def soapTestCase = context.testCase
//Set the request property value (Parameter)
requestPropertyVariable = soapTestCase.getTestStepByName("requestProperty")
requestPropertyVariable.setPropertyValue("affkey",affkey)
requestPropertyVariable.setPropertyValue("etid",etid)
log.info "Reading record " + (i+1) + " from input file"
log.info "Sending request with affkey " + affkey
log.info "Sending request with etid " + etid
//Post a request to webservice
def responseContent = testRunner.runTestStepByName("showetidRequest").getResponse()
def responseText = responseContent.getContentAsString()
//Save the output file
def fileObj = new File("${projectPath}\\API_Response\\${testRunner.testCase.name}\\${etid}_Response.txt")
saveToFile(fileObj, responseText)
//Get the response value
JsonSlurper jsonResponseContent = new JsonSlurper()
def jsonResponseObject = jsonResponseContent.parseText(responseText)
//Validate results
Cell headerParam1 = outputxlsh.getCell(0,0)
Cell headerParam2 = outputxlsh.getCell(1,0)
Cell headerParam3 = outputxlsh.getCell(2,0)
Cell headerParam4 = outputxlsh.getCell(3,0)
Cell headerParam5 = outputxlsh.getCell(4,0)
Cell headerParam6 = outputxlsh.getCell(5,0)
for (k = 0; k < outputRowCount-1; k++) {
Cell responseParam1 = outputxlsh.getCell(0,k+1)
Cell responseParam2 = outputxlsh.getCell(1,k+1)
Cell responseParam3 = outputxlsh.getCell(2,k+1)
Cell responseParam4 = outputxlsh.getCell(3,k+1)
Cell responseParam5 = outputxlsh.getCell(4,k+1)
Cell responseParam6 = outputxlsh.getCell(5,k+1)
expectedAffiliatesWithContent = responseParam1.getContents()
expectedEntityName = responseParam2.getContents()
expectedName = responseParam3.getContents()
expectedSaleMessageId = responseParam4.getContents()
expectedTitle = responseParam5.getContents()
expectedetid = responseParam6.getContents()
if(etid==expectedetid){
responseAffiliatesWithContent = jsonResponseObject.AffiliatesWithContent.getAt(0).getAt(0)
responseEntityName = jsonResponseObject.Genre.EntityName.getAt(0)
responseName = jsonResponseObject.Genre.Name.getAt(0)
responseSaleMessageId = jsonResponseObject.SaleMessage.Id.getAt(0)
responseTitle = jsonResponseObject.Title.getAt(0)
log.info responseAffiliatesWithContent
log.info responseEntityName
log.info responseName
log.info responseSaleMessageId
log.info responseTitle
if (responseAffiliatesWithContent==expectedAffiliatesWithContent&&responseEntityName==expectedEntityName&&responseName==expectedName&&responseSaleMessageId==expectedSaleMessageId&&
responseTitle==expectedTitle)
{
log.info "The data is matched for record " + (k +1) + " hence test case passed "
Label l = new Label(7, k +1, "Pass");
outputxlsh.addCell(l);
xlwb.write();
}
else {
log.info "The data is matched for record " + (k +1) + " hence test case failed "
}
}
}
}
//Clear Property
requestPropertyVariable.setPropertyValue("affkey","")
requestPropertyVariable.setPropertyValue("etid","")
//Write file method
def saveToFile(fileObj, content) {
if (!fileObj.parentFile.exists()) {
fileObj.parentFile.mkdirs()
}
fileObj.write(content)
log.info "Response for etid " + etid + " is stored in " + "${etid}_Response.txt"
assert fileObj.exists(), "${fileObj.name} not created"
}
If you want a write able copy call createWorkbook function
WritableWorkbook xlwb = Workbook.createWorkbook(new File ("${projectPath}\\${testCaseName}.xls"))
If you don't want write able copy save in Workbook object instead
Workbook workbook = Workbook.getWorkbook((new File ("${projectPath}\\${testCaseName}.xls"))
I have achieved the requirement based on below code
def inptDataWb = new HSSFWorkbook(xlwb);
def inputxlsh = inptDataWb.getSheetAt(2);
wrtResult = outputxlsh.getRow(k+1).getCell(3);
wrtResult.setCellValue("P");
wrtResult = outputxlsh.getRow(k+1).getCell(5);
wrtResult.setCellValue("");
inptDataWb.write(xlOwb);