Excel formula is not updating when SOAP UI writes the data - excel

When I run my SOAP UI project, it works fine and it updates the result i.e pass or fail in the specific column however whatever formula I have written which will take input from pass / fail result is not getting updated.
Can you please let me know any reason?
I am using SOAP UI 5.4
The code is given below
import jxl.*;
import java.io.*;
import java.util.Iterator;
import org.apache.poi.ss.usermodel.*;
import static org.apache.poi.ss.usermodel.CellStyle.*;
import static org.apache.poi.ss.usermodel.IndexedColors.*;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator;
import groovy.json.*;
import groovy.utils.*;
def soapTestCase = context.testCase
def requestPropertyVariable = soapTestCase.getTestStepByName("requestProperty")
def globalProperties = com.eviware.soapui.model.propertyexpansion.PropertyExpansionUtils.globalProperties
def responseText = context.expand('${responseText}')
def inputFilePath = globalProperties.getPropertyValue("inputFilePath")
def testDataID = globalProperties.getPropertyValue("testDataID")
def testCaseID = globalProperties.getPropertyValue("testCaseID")
int outputRowCount = Integer.parseInt((requestPropertyVariable.getPropertyValue("outputRowCount")))
def responseStatus = testRunner.testCase.getTestStepByName(testCaseID).getTestRequest().response.responseHeaders.find{ it.key == "#status#" }?.value.getAt(0)
int k = Integer.parseInt((requestPropertyVariable.getPropertyValue("outIteration")))
FileInputStream xlwb = new FileInputStream(new File(inputFilePath));
def inptDataWb = new HSSFWorkbook(xlwb);
def inputxlsh = inptDataWb.getSheetAt(2);
def outputxlsh = inptDataWb.getSheetAt(3);
String otestDataID = outputxlsh.getRow(k+1).getCell(0);
String eleName = outputxlsh.getRow(k+1).getCell(1);
DataFormatter formatter = new DataFormatter();
String expectedResult = formatter.formatCellValue(outputxlsh.getRow(k+1).getCell(2));
String mulEleFLg = outputxlsh.getRow(k+1).getCell(4);
//Validate results
if (responseStatus == "HTTP/1.1 200 OK") {
log.info "Response status code check pass"
def groovyUtils = new com.eviware.soapui.support.GroovyUtils( context )
def responseHolder = groovyUtils.getXmlHolder(testRunner.testCase.testSteps[testCaseID].testRequest.response.getContentAsXml())
def tagElement = responseHolder.getNodeValue(eleName) as String //tagElement is a value of a tag
if(mulEleFLg=="Y"){
responseResultArray = tagElement
multiElementValidation(expectedResult, responseResultArray, inptDataWb, outputxlsh, inputFilePath, k)
}else{
if(expectedResult==tagElement.toString().replaceAll('\\[','').replaceAll('\\]','').trim()){
FileOutputStream xlOwb = new FileOutputStream(new File(inputFilePath));
wrtResult = outputxlsh.getRow(k+1).getCell(3);
wrtResult.setCellValue("P");
wrtResult = outputxlsh.getRow(k+1).getCell(5);
wrtResult.setCellValue("");
inptDataWb.write(xlOwb);
xlOwb.close();
}else{
FileOutputStream xlOwb = new FileOutputStream(new File(inputFilePath));
wrtResult = outputxlsh.getRow(k+1).getCell(3);
wrtResult.setCellValue("F");
wrtResult = outputxlsh.getRow(k+1).getCell(5);
wrtResult.setCellValue("Expected Result is " + expectedResult + " but actual result is " + tagElement.toString().replaceAll('\\[','').replaceAll('\\]',''));
log.info "Expected Result is " + expectedResult + " but actual result is " + tagElement.toString().replaceAll('\\[','').replaceAll('\\]','')
inptDataWb.write(xlOwb);
xlOwb.close();
}
}
FormulaEvaluator evaluator = inptDataWb.getCreationHelper().createFormulaEvaluator();
for (Sheet sheet : inptDataWb) {
for (Row r : sheet) {
for (Cell c : r) {
if (c.getCellType() == Cell.CELL_TYPE_FORMULA) {
evaluator.evaluateAll();
inptDataWb.setForceFormulaRecalculation(true);
log.info "Refreshed"
}
}
}
}
}
def multiElementValidation(expectedResult, responseResultArray, inptDataWb, outputxlsh, inputFilePath, k){
int resResArrCnt = responseResultArray.size()
FileOutputStream xlOwb = new FileOutputStream(new File(inputFilePath));
boolean match = false;
if(resResArrCnt==1){
for (item in responseResultArray)
{
for (itemOfItem in item){
log.info itemOfItem
if(expectedResult==itemOfItem.toString().replaceAll('\\[','').replaceAll('\\]','').trim()){
wrtResult = outputxlsh.getRow(k+1).getCell(3);
wrtResult.setCellValue("P");
wrtResult = outputxlsh.getRow(k+1).getCell(5);
wrtResult.setCellValue("");
inptDataWb.write(xlOwb);
match = true;
break;
}
}
}
}else{
for (item in responseResultArray)
{
if(expectedResult==item.toString().replaceAll('\\[','').replaceAll('\\]','').trim()){
wrtResult = outputxlsh.getRow(k+1).getCell(3);
wrtResult.setCellValue("P");
wrtResult = outputxlsh.getRow(k+1).getCell(5);
wrtResult.setCellValue("");
inptDataWb.write(xlOwb);
match = true;
break;
}
}
}
if(!match){
wrtResult = outputxlsh.getRow(k+1).getCell(3);
wrtResult.setCellValue("F");
wrtResult = outputxlsh.getRow(k+1).getCell(5);
wrtResult.setCellValue("Expected Result is " + expectedResult + " but not exist in the array");
log.info "Expected Result is " + expectedResult + " but not exist in the array"
inptDataWb.write(xlOwb);
}
xlOwb.close()
}
def evaluateWorkbook(){
def inputFilePath = globalProperties.getPropertyValue("inputFilePath")
FileInputStream xlwb = new FileInputStream(new File(inputFilePath));
def inptDataWb = new HSSFWorkbook(xlwb);
FormulaEvaluator evaluator = inptDataWb.getCreationHelper().createFormulaEvaluator();
for (Sheet sheet : inptDataWb) {
for (Row r : sheet) {
for (Cell c : r) {
if (c.getCellType() == Cell.CELL_TYPE_FORMULA) {
evaluator.evaluateFormulaCell(c);
log.info "Refreshed the cell"
}
}
}
}
}

I have handle it in excel macro vba under openworkbook. So the workbook formula get updated when the user opens the workbook

Related

Empty flowfile after trying to write content as Excel

I have following code to read .csv and transform it to Excel:
#Grab("org.apache.poi:poi:5.0.0")
#Grab("org.apache.poi:poi-ooxml:5.0.0")
#Grab("com.opencsv:opencsv:4.6")
import java.io.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.xssf.streaming.*;
import org.apache.poi.ss.SpreadsheetVersion;
import org.apache.poi.ss.util.AreaReference;
import org.apache.poi.ss.util.CellReference;
import com.opencsv.CSVReader;
def flowFile = session.get()
if(!flowFile)
return
flowFile = session.write(flowFile, { inputStream, outputStream ->
try {
SXSSFWorkbook sxssfWorkbook = new SXSSFWorkbook();
CSVReader csvReader = new CSVReader(new InputStreamReader(inputStream));
sxssfWorkbook.setCompressTempFiles(true);
SXSSFSheet sxssfSheet = sxssfWorkbook.createSheet("Sheet");
sxssfSheet.setRandomAccessWindowSize(100);
String[] strHeaders = null;
String[] dataRow = null;
int rowNum = 0;
while ((dataRow = csvReader.readNext()) != null) {
if (rowNum == 0) strHeaders = dataRow;
Row currentRow = sxssfSheet.createRow(rowNum);
for (int i = 0; i < dataRow.length; i++) {
String cellValue = dataRow[i];
currentRow.createCell(i).setCellValue(cellValue);
}
rowNum++;
}
int lastRow = rowNum -1;
int lastCol = strHeaders.length -1;
AreaReference areaReference = new AreaReference(new CellReference(0, 0), new CellReference(lastRow, lastCol), SpreadsheetVersion.EXCEL2007);
XSSFWorkbook xssfWorkbook = sxssfSheet.getWorkbook().getXSSFWorkbook();
XSSFSheet xssfSheet = xssfWorkbook.getSheet(sxssfSheet.getSheetName());
XSSFTable xssfTable = xssfSheet.createTable(areaReference);
//xssfTable.updateHeaders(); // this cannot work since xssfSheet does not contain any data until now
for (int i = 0; i < strHeaders.length; i++) {
String columnHeader = strHeaders[i];
if (xssfTable.getCTTable().getTableColumns().getTableColumnList().size() > i)
xssfTable.getCTTable().getTableColumns().getTableColumnList().get(i).setName(columnHeader);
}
xssfTable.getCTTable().addNewTableStyleInfo();
XSSFTableStyleInfo style = (XSSFTableStyleInfo)xssfTable.getStyle();
style.setName("TableStyleLight9");
style.setShowColumnStripes(false);
style.setShowRowStripes(true);
xssfTable.getCTTable().addNewAutoFilter().setRef(areaReference.formatAsString());
sxssfWorkbook.write(outputStream)
} catch (Exception ex) {
ex.printStackTrace();
}
} as StreamCallback)
session.transfer(flowFile, REL_SUCCESS)
But it returns empty flowfile after ExecuteGroovyScript.
Before I tested this in IntelliJ IDEA with Java. But reading from file and saving to file:
FileOutputStream fileout = new FileOutputStream("P:\\test.xlsx");
CSVReader csvReader = new CSVReader(new FileReader("P:\\test.csv"));
So, I guess something wrong with inputstream/outputstream?
P.S. To test some values from cell I decided to write some value to attributes:
...
sxssfWorkbook.write(outputStream);
flowFile.putAttribute('test', sxssfSheet.getRow(5).getCell(1).toString())
...
But flowfile doesn't contain this attribute.
What did I wrong?

Nexus3 only downloads 50 in list

So I have a code that downloads the version nr of each nuget package but it all stops after 50 in list.
I use jenkins with groovy code and get out a list of versions.
import groovy.json.JsonSlurperClassic
import groovy.json.JsonBuilder
import wslite.rest.*
def data = new URL("http://nexus.xx.xx.se:8081/service/rest/v1/search?repository=xx-sx-nuget&name=XXXFrontend").getText()
println data
/**
* 'jsonString' is the input json you have shown
* parse it and store it in collection
*/
Map convertedJSONMap = new JsonSlurperClassic().parseText(data)
//If you have the nodes then fetch the first one only
if(convertedJSONMap."items"){
println "Version : " + convertedJSONMap."items"[0]."version"
}
def list = convertedJSONMap.items.version
Collections.sort(list)
list
So the problem is that it only get 50 of the versions. How can I get more than 50? I have read about a continuetoken but I dont understand how to use that?
UPDATE
I have added this but still dont work
while(convertedJSONMap."continuesToken" != null){
def token = convertedJSONMap."continuationToken"
def data2 = new URL("http://nexus.xxx.xxx.se:8081/service/rest/v1/search?repository=xxx-xx-nuget&name=xxxxxx&continuationToken=" +token).getText()
convertedJSONMap = JsonSlurperClassic().parseText(data2)
}
This is how I solved it for me. It is just a snippet of the code that I use
def json = sendRequest(url)
addResultToMap(map2, json, release) //I do something here with the received result
def continuationToken = json.continuationToken
if (continuationToken != null) {
while (continuationToken != null) {
json = sendRequest(url + "&continuationToken=" + continuationToken)
addResultToMap(map2, json, release) //I do something here with the received result as above
continuationToken = json.continuationToken
}
}
And my sendRequest method looks like this
def sendRequest(def url, String method = "GET") {
String userPass = "${nexus.username}:${nexus.password}"
String basicAuth = "Basic " + "${printBase64Binary(userPass.getBytes())}"
def connection = new URL( url ).openConnection() as HttpURLConnection
connection.setRequestProperty('Accept', 'application/json' )
connection.setRequestProperty('Authorization', basicAuth)
connection.setRequestMethod(method)
try {
if ( connection.responseCode <= 299 ) {
if (connection.responseCode == 200) {
return connection.inputStream.withCloseable { inStream -> new JsonSlurper().parse( inStream as InputStream ) }
}
} else {
displayAndLogError(connection.responseCode + ": " + connection.inputStream.text, loglevel.DEBUG)
}
} catch(Exception exc) {
displayAndLogError(exc.getMessage())
}
}
Here is an alternative :
import groovy.json.JsonSlurper
try {
N_PAGES_MAX = 10
List<String> versions = new ArrayList<String>()
continuationToken = "123"
artifactsUrl = "http://nexus.zzz.local/service/rest/v1/components?repository=releases-super-project"
currentPage = 1
while (true) {
artifactsObjectRaw = ["curl", "-s", "-H", "accept: application/json", "-k", "--url", "${artifactsUrl}"].execute().text
artifactsJsonObject = (new JsonSlurper()).parseText(artifactsObjectRaw)
continuationToken = artifactsJsonObject.continuationToken
if (continuationToken!=null && continuationToken!='123') {
artifactsUrl = artifactsUrl + "&continuationToken=$continuationToken"
}
def items = artifactsJsonObject.items
for(item in items){
versions.add(item.name)
}
currentPage += 1
if (continuationToken==null || currentPage>N_PAGES_MAX) break
}
return versions.sort().reverse()
}
catch (Exception e) {
print "There was a problem fetching the versions"
}

Using Epplus to import data from an Excel file to SQL Server database table

I've tried implementing thishttps://www.paragon-inc.com/resources/blogs-posts/easy_excel_interaction_pt6 on an ASP.NET MVC 5 Application.
//SEE CODE BELOW
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
var regPIN = DB.AspNetUsers.Where(i => i.Id == user.Id).Select(i => i.registrationPIN).FirstOrDefault();
if (file != null && file.ContentLength > 0)
{
var extension = Path.GetExtension(file.FileName);
var excelFile = Path.Combine(Server.MapPath("~/App_Data/BulkImports"),regPIN + extension);
if (System.IO.File.Exists(excelFile))
{
System.IO.File.Delete(excelFile);
}
else if (file.ContentType == "application/vnd.ms-excel" || file.ContentType == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
{
file.SaveAs(excelFile);//WORKS FINE
//BEGINING OF IMPORT
FileInfo eFile = new FileInfo(excelFile);
using (var excelPackage = new ExcelPackage(eFile))
{
if (!eFile.Name.EndsWith("xlsx"))//Return ModelState.AddModelError()
{ ModelState.AddModelError("", "Incompartible Excel Document. Please use MSExcel 2007 and Above!"); }
else
{
var worksheet = excelPackage.Workbook.Worksheets[1];
if (worksheet == null) { ModelState.AddModelError("", "Wrong Excel Format!"); }// return ImportResults.WrongFormat;
else
{
var lastRow = worksheet.Dimension.End.Row;
while (lastRow >= 1)
{
var range = worksheet.Cells[lastRow, 1, lastRow, 3];
if (range.Any(c => c.Value != null))
{ break; }
lastRow--;
}
using (var db = new BlackBox_FinaleEntities())// var db = new BlackBox_FinaleEntities())
{
for (var row = 2; row <= lastRow; row++)
{
var newPerson = new personalDetails
{
identificationType = worksheet.Cells[row, 1].Value.ToString(),
idNumber = worksheet.Cells[row, 2].Value.ToString(),
idSerial = worksheet.Cells[row, 3].Value.ToString(),
fullName = worksheet.Cells[row, 4].Value.ToString(),
dob = DateTime.Parse(worksheet.Cells[row, 5].Value.ToString()),
gender = worksheet.Cells[row, 6].Value.ToString()
};
DB.personalDetails.Add(newPerson);
try { db.SaveChanges(); }
catch (Exception) { }
}
}
}
}
}//END OF IMPORT
ViewBag.Message = "Your file was successfully uploaded.";
return RedirectToAction("Index");
}
ViewBag.Message = "Error: Your file was not uploaded. Ensure you upload an excel workbook file.";
return View();
}
else
{
ViewBag.Message = "Error: Your file was not uploaded. Ensure you upload an excel workbook file.";
return View();
}
}
See Picture Error
Any help would be greatly appreciated mates.
you can do like this:
public bool readXLS(string FilePath)
{
FileInfo existingFile = new FileInfo(FilePath);
using (ExcelPackage package = new ExcelPackage(existingFile))
{
//get the first worksheet in the workbook
ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
int colCount = worksheet.Dimension.End.Column; //get Column Count
int rowCount = worksheet.Dimension.End.Row; //get row count
string queryString = "INSERT INTO tableName VALUES"; //Here I am using "blind insert". You can specify the column names Blient inset is strongly not recommanded
string eachVal = "";
bool status;
for (int row = 1; row <= rowCount; row++)
{
queryString += "(";
for (int col = 1; col <= colCount; col++)
{
eachVal = worksheet.Cells[row, col].Value.ToString().Trim();
queryString += "'" + eachVal + "',";
}
queryString = queryString.Remove(queryString.Length - 1, 1); //removing last comma (,) from the string
if (row % 1000 == 0) //On every 1000 query will execute, as maximum of 1000 will be executed at a time.
{
queryString += ")";
status = this.runQuery(queryString); //executing query
if (status == false)
return status;
queryString = "INSERT INTO tableName VALUES";
}
else
{
queryString += "),";
}
}
queryString = queryString.Remove(queryString.Length - 1, 1); //removing last comma (,) from the string
status = this.runQuery(queryString); //executing query
return status;
}
}
Details: http://sforsuresh.in/read-data-excel-sheet-insert-database-table-c/

table component not working in lwuit?

I want to display the table after selecting the values from comboBox. It working first time selection after that it adding another two more table in UI.
Can anyone say how to fix this?
Here the code:
package com.onmo.classes;
import java.io.IOException;
import com.sun.lwuit.Button;
import com.sun.lwuit.ComboBox;
import com.sun.lwuit.Command;
import com.sun.lwuit.Component;
import com.sun.lwuit.Container;
import com.sun.lwuit.Form;
import com.sun.lwuit.Image;
import com.sun.lwuit.Label;
import com.sun.lwuit.TabbedPane;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.events.ActionListener;
import com.sun.lwuit.events.SelectionListener;
import com.sun.lwuit.layouts.BorderLayout;
import com.sun.lwuit.layouts.BoxLayout;
import com.sun.lwuit.layouts.FlowLayout;
import com.sun.lwuit.plaf.UIManager;
import com.sun.lwuit.table.DefaultTableModel;
import com.sun.lwuit.table.Table;
import com.sun.lwuit.table.TableModel;
import com.sun.lwuit.util.Resources;
public class CompareScreen implements ActionListener, SelectionListener {
private Command enterCmd;
private Command backCmd;
private Command exitCmd;
private Form comparePage;
private Label lblLeagues, lblTeam;
private Button btnTeams, btnPlayers;
private FlowLayout flowLayout;
private ComboBox comboTeamA, comboTeamB, comboTeamC, comboTeamD, player1,
player2;
private Image firstTeamImage, secondTeamImage = null;
private Container teamsContainer, teamCombo, teamImages, playersTeamTab,
playersContainer, playersTab, playerImages;
int count = 0;
CompareScreen(){
enterCmd = new Command("Select");
backCmd = new Command("Back");
exitCmd = new Command("Exit");
}
public void displayCompareScreen() {
comparePage = new Form();
// comparePage.getStyle().setBgColor(0xaa00ff);
String[] teamA = { "Team A", "Villarreal", "Violent Vegans",
"Venom XI", "Betis" };
String[] teamB = { "Team B", "Villarreal", "Violent Vegans",
"Venom XI", "Betis" };
String[] playerList1 = { "Player1", "Acho, Sam", "Adams, Mike",
"Ajirotutu, Seyi", "Abel Gomez" };
String[] playerList2 = { "Player2", "Acho, Sam", "Adams, Mike",
"Ajirotutu, Seyi", "Abel Gomez" };
comparePage.addCommand(backCmd);
comparePage.addCommandListener(this);
lblLeagues = new Label("Premier League");
lblTeam = new Label("Team");
btnTeams = new Button("Teams");
btnPlayers = new Button("Players");
comboTeamA = new ComboBox(teamA);
comboTeamB = new ComboBox(teamB);
comboTeamC = new ComboBox(teamA);
comboTeamD = new ComboBox(teamB);
player1 = new ComboBox(playerList1);
player2 = new ComboBox(playerList2);
comparePage.setLayout(new BorderLayout());
comparePage
.addComponent(BorderLayout.WEST, new Label("Premier League"));
comparePage.addComponent(BorderLayout.EAST, new Label("Compare"));
flowLayout = new FlowLayout();
comparePage.setLayout(flowLayout);
try {
Resources r = Resources.open("/theme/javathema.res");
UIManager.getInstance().setThemeProps(r.getTheme("javathema"));
} catch (IOException ioe) {
System.out.println("Couldn't load theme.");
}
try {
firstTeamImage = Image.createImage("/team1.png");
secondTeamImage = Image.createImage("/team2.png");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Label lblFirstTeam = new Label(firstTeamImage);
lblFirstTeam.setAlignment(Component.LEFT);
Label lblSecondTeam = new Label(secondTeamImage);
lblSecondTeam.setAlignment(Component.RIGHT);
Label lblFirstPlayer = new Label(firstTeamImage);
lblFirstTeam.setAlignment(Component.LEFT);
Label lblSecondPlayer = new Label(secondTeamImage);
lblSecondTeam.setAlignment(Component.RIGHT);
teamsContainer = new Container(new BoxLayout(BoxLayout.Y_AXIS));
teamCombo = new Container(new BoxLayout(BoxLayout.X_AXIS));
teamCombo.addComponent(comboTeamA);
teamCombo.addComponent(comboTeamB);
teamImages = new Container(new BoxLayout(BoxLayout.X_AXIS));
teamImages.addComponent(lblFirstTeam);
teamImages.addComponent(lblSecondTeam);
teamsContainer.addComponent(teamCombo);
teamsContainer.addComponent(teamImages);
playersTeamTab = new Container(new BoxLayout(BoxLayout.X_AXIS));
playersTeamTab.addComponent(comboTeamC);
playersTeamTab.addComponent(comboTeamD);
playersTab = new Container(new BoxLayout(BoxLayout.X_AXIS));
playersTab.addComponent(player1);
playersTab.addComponent(player2);
playerImages = new Container(new BoxLayout(BoxLayout.X_AXIS));
playerImages.addComponent(lblFirstPlayer);
playerImages.addComponent(lblSecondPlayer);
playersContainer = new Container(new BoxLayout(BoxLayout.Y_AXIS));
playersContainer.addComponent(playersTeamTab);
playersContainer.addComponent(playersTab);
playersContainer.addComponent(playerImages);
TabbedPane tabbedPane = new TabbedPane(TabbedPane.TOP);
tabbedPane.addTab("Teams", teamsContainer);
tabbedPane.addTab("Players", playersContainer);
// comboTeamA.addSelectionListener(this);
comboTeamB.addSelectionListener(this);
// comboTeamC.addSelectionListener(this);
comboTeamD.addSelectionListener(this);
// comboTeamA.addActionListener(this);
comparePage.addComponent(tabbedPane);
comparePage.show();
}
public void selectionChanged(int arg0, int arg1) {
// TODO Auto-generated method stub
System.out.println("Before :" + count);
Table tableTeam = null, tablePlayer = null;
if (comboTeamA.getSelectedIndex() != 0 && comboTeamB.getSelectedIndex() != 0 && comboTeamC.getSelectedIndex() == 0 && comboTeamD.getSelectedIndex() == 0) {
TableModel model = new DefaultTableModel(new String[] { "10 ",
"Games Played", "10" }, new Object[][] {
{ "7 ", "Wins", " 6" }, { "2 ", "Draws", " 1" },
{ "1 ", "Defeats", " 1" }, { "10 ", "Goals for", " 8" }, });
tableTeam = new Table(model);
if (count == 1) {
teamsContainer.addComponent(tableTeam);
count = 0;
}
count = count + 1;
System.out.println("On :" + count);
}
if (comboTeamA.getSelectedIndex() == 0 && comboTeamB.getSelectedIndex() == 0 && comboTeamC.getSelectedIndex() != 0 && comboTeamD.getSelectedIndex() != 0) {
TableModel model = new DefaultTableModel(new String[] { "10 ",
"Games Played", "10" }, new Object[][] {
{ "260 ", "Minutes Played", " 280" },
{ "240 ", "Starts", " 230" },
{ "20 ", "Substitute", " 30" },
{ "6 ", "Goals for", " 9" }, });
tablePlayer = new Table(model);
if (count == 1) {
playersContainer.addComponent(tablePlayer);
count = 0;
}
count = count + 1;
System.out.println("On :" + count);
}
/*
* if(tableTeam != null && tablePlayer != null) {
* teamsContainer.removeComponent(tableTeam);
* playersContainer.removeComponent(tablePlayer); }
*/
System.out.println("After :" + count);
}
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
HomePage homePageObj=HomePage.getInstance();
homePageObj.displayHomePage();
}
}
The problem is at this code:
public void selectionChanged(int arg0, int arg1) {
...
tableTeam = new Table(model);
if (count == 1) {
teamsContainer.addComponent(tableTeam);
count = 0;
}
count = count + 1;
...
}
This code snippet means that you add another Table each time you select another value from the ComboBox : DON'T RESET "count" TO 0 !

Groovy and POI: Can I read/write at the same time?

I'm new to groovy, and I've used the ExcelBuilder code referenced below to iterate through an excel spreadsheet to grab data. Is there an easy to write data as I iterate?
For example, row 1 might have data like this (CSV):
value1,value2
And after I iterate, I want it to look like this:
value1,value2,value3
http://www.technipelago.se/content/technipelago/blog/44
Yes, this can be done! As I got into the guts of it, I realized that the problem I was trying to solve wasn't the same as trying to read and write from the same file at the same time, but rather the excel data was stored in an object that I could freely manipulate whenever I wanted. So I added methods specific to my needs - which may or many not meet the needs of anyone else - and I post them here for smarter people to pick apart. At the end of it all, it is now doing what I want it to do.
I added a cell method that takes an index (number or label) and a value which will update a cell for the current row in context (specifically while using .eachLine()), and a .putRow() method that adds a whole row to the spreadsheet specified. It also handles Excel 2003, 2007, and 2010 formats. When files, sheets, or cells referenced don't exist, they get created. Since my source spreadsheets often have formulas and charts ready to display the data I'm entering, the .save() and .saveAs() methods call .evaluateAllFormulaCells() before saving.
To see the code I started with and examples of how it works, check out this blog entry
Note that both the .save() and .saveAs() methods reload the workbook from the saved file immediately after saving. This is a workaround to a bug in Apache POI that doesn't seem to be fixed yet (see Exception when writing to the xlsx document several times using apache poi).
import groovy.lang.Closure;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Map;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.xssf.usermodel.XSSFFormulaEvaluator;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator;
class Excel
{
def workbook;
def sheet;
def labels;
def row;
def infilename;
def outfilename;
Excel(String fileName)
{
HSSFRow.metaClass.getAt = {int index ->
def cell = delegate.getCell(index);
if(! cell)
{
return null;
}
def value;
switch (cell.cellType)
{
case HSSFCell.CELL_TYPE_NUMERIC:
if(HSSFDateUtil.isCellDateFormatted(cell))
{
value = cell.dateCellValue;
}
else
{
value = new DataFormatter().formatCellValue(cell);
}
break;
case HSSFCell.CELL_TYPE_BOOLEAN:
value = cell.booleanCellValue
break;
default:
value = new DataFormatter().formatCellValue(cell);
break;
}
return value
}
XSSFRow.metaClass.getAt = {int index ->
def cell = delegate.getCell(index);
if(! cell)
{
return null;
}
def value = new DataFormatter().formatCellValue(cell);
switch (cell.cellType)
{
case XSSFCell.CELL_TYPE_NUMERIC:
if (DateUtil.isCellDateFormatted(cell))
{
value = cell.dateCellValue;
}
else
{
value = new DataFormatter().formatCellValue(cell);
}
break;
case XSSFCell.CELL_TYPE_BOOLEAN:
value = cell.booleanCellValue
break;
default:
value = new DataFormatter().formatCellValue(cell);
break;
}
return value;
}
infilename = fileName;
outfilename = fileName;
try
{
workbook = WorkbookFactory.create(new FileInputStream(infilename));
}
catch (FileNotFoundException e)
{
workbook = (infilename =~ /(?is:\.xlsx)$/) ? new XSSFWorkbook() : new HSSFWorkbook();
}
catch (Exception e)
{
e.printStackTrace();
}
}
def getSheet(index)
{
def requested_sheet;
if(!index) index = 0;
if(index instanceof Number)
{
requested_sheet = (workbook.getNumberOfSheets >= index) ? workbook.getSheetAt(index) : workbook.createSheet();
}
else if (index ==~ /^\d+$/)
{
requested_sheet = (workbook.getNumberOfSheets >= Integer.valueOf(index)) ? workbook.getSheetAt(Integer.valueOf(index)) : workbook.createSheet();
}
else
{
requested_sheet = (workbook.getSheetIndex(index) > -1) ? workbook.getSheet(index) : workbook.createSheet(index);
}
return requested_sheet;
}
def cell(index)
{
if (labels && (index instanceof String))
{
index = labels.indexOf(index.toLowerCase());
}
if (row[index] == null)
{
row.createCell(index);
}
return row[index];
}
def cell(index, value)
{
if (labels.indexOf(index.toLowerCase()) == -1)
{
labels.push(index.toLowerCase());
def frow = sheet.getRow(0);
def ncell = frow.createCell(labels.indexOf(index.toLowerCase()));
ncell.setCellValue(index.toString());
}
def cell = (labels && (index instanceof String)) ? row.getCell(labels.indexOf(index.toLowerCase())) : row.getCell(index);
if (cell == null)
{
cell = (index instanceof String) ? row.createCell(labels.indexOf(index.toLowerCase())) : row.createCell(index);
}
cell.setCellValue(value);
}
def putRow (sheetName, Map values = [:])
{
def requested_sheet = getSheet(sheetName);
if (requested_sheet)
{
def lrow;
if (requested_sheet.getPhysicalNumberOfRows() == 0)
{
lrow = requested_sheet.createRow(0);
def lcounter = 0;
values.each {entry->
def lcell = lrow.createCell(lcounter);
lcell.setCellValue(entry.key);
lcounter++;
}
}
else
{
lrow = requested_sheet.getRow(0);
}
def sheetLabels = lrow.collect{it.toString().toLowerCase()}
def vrow = requested_sheet.createRow(requested_sheet.getLastRowNum() + 1);
values.each {entry->
def vcell = vrow.createCell(sheetLabels.indexOf(entry.key.toLowerCase()));
vcell.setCellValue(entry.value);
}
}
}
def propertyMissing(String name)
{
cell(name);
}
def propertyMissing(String name, value)
{
cell(name, value);
}
def eachLine (Map params = [:], Closure closure)
{
/*
* Parameters:
* skiprows : The number of rows to skip before the first line of data and/or labels
* offset : The number of rows to skip (after labels) before returning rows
* max : The maximum number of rows to iterate
* sheet : The name (string) or index (integer) of the worksheet to use
* labels : A boolean to treat the first row as a header row (data can be reference by label)
*
*/
def skiprows = params.skiprows ?: 0;
def offset = params.offset ?: 0;
def max = params.max ?: 9999999;
sheet = getSheet(params.sheet);
def rowIterator = sheet.rowIterator();
def linesRead = 0;
skiprows.times{ rowIterator.next() }
if(params.labels)
{
labels = rowIterator.next().collect{it.toString().toLowerCase()}
}
offset.times{ rowIterator.next() }
closure.setDelegate(this);
while(rowIterator.hasNext() && linesRead++ < max)
{
row = rowIterator.next();
closure.call(row);
}
}
def save ()
{
if (workbook.getClass().toString().indexOf("XSSF") > -1)
{
XSSFFormulaEvaluator.evaluateAllFormulaCells((XSSFWorkbook) workbook);
}
else
{
HSSFFormulaEvaluator.evaluateAllFormulaCells((HSSFWorkbook) workbook);
}
if (outfilename != null)
{
try
{
FileOutputStream output = new FileOutputStream(outfilename);
workbook.write(output);
output.close();
workbook = null;
workbook = WorkbookFactory.create(new FileInputStream(outfilename));
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
def saveAs (String fileName)
{
if (workbook.getClass().toString().indexOf("XSSF") > -1)
{
XSSFFormulaEvaluator.evaluateAllFormulaCells((XSSFWorkbook) workbook);
}
else
{
HSSFFormulaEvaluator.evaluateAllFormulaCells((HSSFWorkbook) workbook);
}
try
{
FileOutputStream output = new FileOutputStream(fileName);
workbook.write(output);
output.close();
outfilename = fileName;
workbook = null;
workbook = WorkbookFactory.create(new FileInputStream(outfilename));
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
If you see any glaring errors or ways to improve (other than style), I'd love to hear them. Again, Groovy is not a language I have much experience with, and I haven't done anything with Java in several years, so I'm sure there might be some better ways to do things.

Resources