How to write formatted numbers as numbers in JExcel (jxl) - java

I am using Java Spring and jxl to create Excel workbook on server side. The data that needs to be shown in Excel consists of already formatted numbers. I am using
WritableCellFormat wcf = new WritableCellFormat();
wcf.setAlignment(Alignment.RIGHT);
....
....
sheet.addCell(new Label(j, i + 1, xxx, wcf));
//where xxx is a string which is a number already formatted
In the downloaded excel file, all these numbers are stored as text and so Excel can't use formulas on them, it gives a warning as 'Number stored as Text' and I have to do 'Convert to Number'.
In jxl, can we pass strings and tell to interpret them as numbers? All the numbers I have are valid numbers formatted differently using $, %, thousands separators. I don't want to convert them to valid numbers and give them formatting again while exporting to excel.
Please help. Thank you.

I had a similar problem
I changed the variable to int and used new Number function it helped.
int eday = Integer.parseInt(Trainingresult.getString("Day"));
//Label Eday = new Label(1, i, eday);
firstsheet.addCell(new Number(1,i,eday));

/*use new Number to write number cell*/
WritableWorkbook w;
try {
w = Workbook.createWorkbook(new File("c:/test.xls"));
WritableSheet s = w.createSheet("Demo Book", 0);
WritableCellFormat wcf = new WritableCellFormat();
for (int i=0;i<10;i++){
int row = i+1;
/*add cell number*/
s.addCell(new Number(1, i, (i*15)));
/*add cell number*/
s.addCell(new Number(2, i, (i*3+Math.random()*10)));
/*add formula*/
s.addCell(new Formula(3,i,"B"+row+" * C"+row));
}
w.write();
w.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (RowsExceededException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (WriteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

first, add import
import jxl.write.Number;
because you could get other Number class and get error,
after that do anything
double dval = 1;
Number number = new Number(k, n, dval);
So you could also useful this codes
if(readCell.getType() == CellType.BOOLEAN) {
boolean bv = false;
if(readCell.getContents().equals("true")) {
bv = true;
}
Boolean b = new Boolean(i,j,bv);
writesheet.addCell(b);
} else
if(readCell.getType() == CellType.NUMBER) {
//if (!readCell.getContents().equals("")) {
double dval = 0;
try {
dval = Double.parseDouble(readCell.getContents());
} catch (NumberFormatException ex) {
}
Number n = new Number(i, j, dval);
writesheet.addCell(n);

Related

How do i write in Excel file the value of individual popup and each popup contains the table

The below code executes on 21 rows and, when clicking on each row, a popup appears which contains a table that I need to write to an Excel file.
Row 0, 1,2 and 3 are just printing the name of page and other headings.
From the row 5th it should print each table of each popup(21 popups value).
Following code writing only last measure and also printing only the last row of that particular table(popup). I don't know to increment the rows for next popup/table to write on excel also need to increase the number of rows for a inner loop for(int j=0;j<totalNoOfLOB.size();j++) to print all values.
And int totalNoOfPopupRows =totalNoOfRows+1; gives me the total number of rows for each popup. Any help will be appreciated.
public void measureDetail() throws Exception {
Actions act = new Actions(driver);
clickOnAllMeasureListOneAfterOther.forEach(s - > {
try {
Thread.sleep(3000);
s.click();
FileOutputStream fos = new FileOutputStream("C:\\Users\\pdholakia\\Desktop\\N4.xls");
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet("PCP_Performance");
sheet.createRow(0).createCell(0).setCellValue(moduleName.getText());
sheet.createRow(1).createCell(0).setCellValue(pageName.getText());
sheet.createRow(2).createCell(0).setCellValue(hierarchy.getText());
sheet.createRow(2).createCell(1).setCellValue(hierarchyOption.getText());
sheet.createRow(3).createCell(0).setCellValue(program.getText());
sheet.createRow(3).createCell(1).setCellValue(programOption.getText());
int totalNoOfRows = driver.findElements(By.xpath("//div[#id='divMeasureDetails']/table/tbody/trxpathExpression")).size();
int totalNoOfPopupRows = totalNoOfRows + 1;
//totalNoOfPopupRows is giving me the size of every popup, the number of rows of popup are dynamic.
int row = 5;
String measureName1 = measureName.getText();
System.out.println("*********************************************************************************************");
System.out.println("MEASURE NAME::::-" + measureName1);
sheet.createRow(row).createCell(0).setCellValue(measureName1);
///////Code for Row 1 of pupup/////////
String com = combinedText.getText();
System.out.format("%8s", com);
sheet.createRow(row + 1).createCell(0).setCellValue(com);
for (int cRow = 0; cRow < combinedRowValues.size(); cRow++) {
String combinedRowValue = combinedRowValues.get(cRow).getText();
System.out.format("%10s", combinedRowValue);
sheet.getRow(row + 1).createCell(cRow + 1).setCellValue(combinedRowValue);
}
String numeratorDenominatorValue = numeratorDenominator.getText();
System.out.format("%20s", numeratorDenominatorValue);
sheet.getRow(row + 1).createCell(4).setCellValue(numeratorDenominatorValue);
/////// Code for Row 2 of pupup/////////
System.out.println("\n");
System.out.println("Business Line(LOB) | Performance | Minimum_Threshold | Actual Values | To Target ");
sheet.createRow(row + 2).createCell(0).setCellValue("Business Line");
sheet.getRow(row + 2).createCell(1).setCellValue("Performance");
sheet.getRow(row + 2).createCell(2).setCellValue("Minimum_Threshold");
sheet.getRow(row + 2).createCell(3).setCellValue("Actual Values");
sheet.getRow(row + 2).createCell(4).setCellValue("To Target");
////// Code for Row 3/4/5. of popup ///////
for (int j = 0; j < totalNoOfLOB.size(); j++)(totlNoOfLob can be 1 / 2 / 3 or 4) {
System.out.format("%15s", totalNoOfLOB.get(j).getText());
sheet.createRow(row + 3).createCell(0).setCellValue(totalNoOfLOB.get(j).getText());
System.out.format("%15s", combinedPerformanceOfMeasure.get(j + 3).getText());
sheet.getRow(row + 3).createCell(1).setCellValue(totalNoOfLOB.get(j).getText());
System.out.format("%15s", thresdhholdsLowerValues.get(j).getText());
sheet.getRow(row + 3).createCell(2).setCellValue(thresdhholdsLowerValues.get(j).getText());
System.out.format("%25s", listOfActualValues.get(j + 1).getText());
sheet.getRow(row + 3).createCell(3).setCellValue(listOfActualValues.get(j + 1).getText());
System.out.format("%15s", listOfToTarget.get(j).getText());
sheet.getRow(row + 3).createCell(4).setCellValue(listOfActualValues.get(j + 1).getText());
System.out.println("\n");
}
try {
fos.flush();
wb.write(fos);
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
act.moveToElement(labelProgram).click().build().perform();
});
}
}

compare lines in JTextArea

Im working on a project where I create an online-shop-like application. Have everything working apart from last thing, which is reading the whole basket(items added to basket)
I have a button that adds item to the order(they are displayed in jtextarea).
I have another button that finishes shopping and is supposed to print your items which were added to jtextarea. Unfortunately I was only able to figure out how to read the last line in jtextarea. so basically what happens :
customer orders x, amount 1
customer orders y, amount 3
customer orders z, amount 7
It will only print the last line. any suggestion?
Here is the code
btnFinish.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int end = textArea.getDocument().getLength();
int start = 0;
try {
start = Utilities.getRowStart(textArea, end);
} catch (BadLocationException e1) {
e1.printStackTrace();
}
while (start == end)
{
end--;
try {
start = Utilities.getRowStart(textArea, end);
} catch (BadLocationException e1) {
e1.printStackTrace();
}
}
String text = null;
try {
text = textArea.getText(start, end - start);
} catch (BadLocationException e1) {
e1.printStackTrace();
}
System.out.println("(" + text + ")"); ```

how to implement a linked list properly using java

I am working in a project with linked list (JAVA) but I am not being able to figure out how to insert the person. How could I get the switch to work? Or should I use something else? I also thought about creating a class outside the main method and just call it but it did not work as well. Any help will be much appreciate
public void listOfPeople() { // Beginning of the method listOfPeople where shows the employees
// *** instance the person object ad loading your variables
Personqueue p1 = new Personqueue(); //saving the employee in a variable???
p1.setFname("John");
p1.setLname("Smith");
p1.setDOA(15);
p1.setPassportN(306589);
p1.setNumber(1);
vectorObj.add(p1); // add the employee in a vector
Personqueue p2 = new Personqueue(); //saving the employee in a variable???
p1.setFname("Paul");
p1.setLname("Clooney");
p1.setDOA(5);
p1.setPassportN(30614584);
p1.setNumber(2);
vectorObj.add(p2); // add the employee in a vector
}
public void ascendingOrder(Vector<Personqueue> vector) { // bubble sort method to order the vector
int j;
boolean flag = true; // set flag to true to begin first pass
Personqueue temp; // holding the variable temporarily
while (flag) {
flag = false; // set flag to false awaiting a possible swap
for (j = 0; j < vector.size() - 1; j++) {
if (vector.get(j).getNumber() > vector.get(j + 1).getNumber()) {
temp = vector.get(j); // swap elements
vector.set(j, vector.get(j + 1));
vector.set(j + 1, temp);
flag = true; // shows a swap occurred
}
}
}
}
public void newPerson(int positionPerson) { // beginning of newPerson method
String Option = null; // declaration of local variables that are used only in this method and don't use too much space
Personqueue p = new Personqueue(); //instead of setting it to null, here we are calling
// a constructor which was declared in Personqueue class.
// switch (positionPerson) {
// case 1: // insert a person at the start of the queue
// // p = new QueueStart();
// break; // executes in order to end the switch in case one of the options is valid
// case 2: // insert a person at a chosen point in the queue
// // p = new ChoosePosition();
// case 3: // insert a person at the end of the queue
// // p = new EndQueue();
// break;
// default:
// System.out.println("Invalid Option!!!"); // in case the option is not one of the cases above, print this...
// return; // return to the do/while loop in Principal method
// }
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Name:"); // user input
try {
Option = br.readLine();
String name = Option;
p.setFname(name);
} catch (IOException e) {
System.out.println(e);
}
System.out.println("Surname:"); // user input
try {
Option = br.readLine();
String lname = Option;
p.setLname(lname);
} catch (IOException e) {
System.out.println(e);
}
System.out.println("Date Of Arrival: "); // user input
try {
Option = br.readLine();
int doa = Integer.parseInt(Option); // use parseInt in order to convert Integer to String to be read by BufferedReader.
p.setDOA(doa);
} catch (IOException e) {
System.out.println(e);
}
System.out.println("Passport Number:"); // user input
try {
Option = br.readLine();
int pn = Integer.parseInt(Option);
p.setPassportN(pn);
} catch (IOException e) {
System.out.println(e);
}
System.out.println("Number:"); // user input
try {
Option = br.readLine();
int no = Integer.parseInt(Option);
p.setNumber(no);
} catch (IOException e) {
System.out.println(e);
}
vectorObj.addElement(p); // save all the data in the vector
System.out.print("Saving Person :" + p.getFname()); // print to the user the name's been saved
try {
for (int i = 0; i < 6; i++) {
System.out.print(".");
Thread.sleep(300); // suspend the "." execution for a specified period.
}
} catch (InterruptedException e) { // exception p o method thread // catch for thread above
e.printStackTrace();
}
System.out.println();
System.out.println("Person: " + p.getFname() + " is saved!!!");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
} // end of the Method newPerson
Check your variables in listOfPeople(...), p2 was not used correctly.
Take a look at Example of LinkedList in Java

for loop with ArrayList in java

i got a Productclass stored in ArrayList myValues.
I want to go trough each xth ( for example each 3th) element and have the user
add some Integer values to that class.
In my for(...) he tells me: The left-hand side of an assignment must be a variable. I wonder if i messed up some of the .get(j) or if i have to synchronize my methods so that the size wont change ( there is no multi-threading but maybe thats why i get an error?
) or the solution is more simple.
Thx
public void prioPerProduct (){
System.out.println("");
System.out.println("Please enter storing and upgrading cost:");
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
int storingCost = 0;
int ruestCost = 0;
int countRes = countRessources;
int sizemyValues = myValues.size();
for(int j = 0; j < sizemyValues; j = j+countRes){
System.out.println("Please enter storingcost " + myValues.get(j).getProduct() +":" );
try {
storingCost = Integer.valueOf(br.readLine());
} catch (NumberFormatException e) {
System.out.println("No number entered");
e.printStackTrace();
} catch (IOException e) {
System.out.println("No number entered");
e.printStackTrace();
}
System.out.println("Please enter upgradingcost " + myValues.get(j).getProduct() +":" );
try {
ruestCost = Integer.valueOf(br.readLine());
} catch (NumberFormatException e) {
System.out.println("No number entered");
e.printStackTrace();
} catch (IOException e) {
System.out.println("No number entered");
e.printStackTrace();
}
myValues.get(j).setstoringCost(storingCost);
myValues.get(j).setupgradingCost(ruestCost);
}
}
The left-hand side of an assignment must be a variable is generally caused by something like this:
methodCall() = somvalue...
The left hand side must be a variable rather than a method call. Your code looks fine in this regard.
The code where you declare your model class and a full stack trace are more helpful.
Use the set method to change the value of an object inside of an ArrayList.
myValues.set(j,myValues.get().setstoringCost(storingCost));
myValues.set(j,myValues.get().setupgradingCost(ruestCost));

Apache poi. Formula evalution. evaluteAll vs setForceFormulaRecalculation

[better quality]:. http://imageshack.us/photo/my-images/51/v5cg.png/
Problem: i use formulas in my workBook.xlsx. Depending on the circumstances i change value (3,3). At this example i changed 10 to 20. And after that i want to calculate the formula, which use this cell. When it has finished, it will override the value of the cells, remove formula and record the value. This cell no longer be used for the calculations again.
Code:
public class ReaderXlsx {
public List<List<String>> ReaderXlsx(String sfilename, int firstColumn, int columnsCount, int rowsCount, int moduleCount){
int lastColumn=firstColumn+columnsCount;
List<List<String>> rowsContent = new ArrayList<List<String>>();
try ( FileInputStream fileInputStream = new FileInputStream("C:\\Users\\student3\\"+sfilename+".xlsx");)
{
XSSFWorkbook workBook = new XSSFWorkbook(fileInputStream);
XSSFSheet sheet = workBook.getSheetAt(0);
int firstRow = findOneInFirstColumn(sheet,50);
setModuleCount(sheet,moduleCount);
workBook.getCreationHelper().createFormulaEvaluator().evaluateAll();
toNewLine:
for (int lineId=firstRow;lineId<rowsCount;lineId++) {
List<String> columnsContent = new ArrayList<String>();
Row row = sheet.getRow(lineId);
if (row==null){continue toNewLine;}
if (row.getCell(2)==null || row.getCell(2).getStringCellValue().equals("") ) {continue toNewLine;}
for (int columnId=firstColumn+1;columnId<lastColumn;columnId++) {
Cell cell = row.getCell(columnId-1);
if ((cell==null)) { continue toNewLine;}
cell.setCellType(Cell.CELL_TYPE_STRING);
if ((columnId==0 & cell.getStringCellValue().equals(""))) {continue toNewLine;}
if ((columnId==5 & cell.getStringCellValue().equals("")) || (columnId==6 & cell.getStringCellValue().equals(""))) cell.setCellValue("0");
columnsContent.add(cell.getStringCellValue());
}
rowsContent.add(columnsContent);
}
try(FileOutputStream out = new FileOutputStream("C:\\Users\\student3\\Used"+sfilename+".xlsx"); ) {
workBook.write(out);
out.close(); }
}
catch (IOException e) {
e.printStackTrace();
}
return rowsContent;
}
private Integer findOneInFirstColumn(XSSFSheet sheet, Integer maxRows){
int result=0;
toNextLine:
for (int lineId=0;lineId<maxRows;lineId++){
Row row = sheet.getRow(lineId);
if (row==null | row.getCell(0)==null) {result++; continue toNextLine; }
else{
row.getCell(0).setCellType(Cell.CELL_TYPE_STRING);
if (row.getCell(0).getStringCellValue().equals("1")){return result;}
else {result++;}
}
}
return result;
}
private void setModuleCount(XSSFSheet sheet, Integer moduleCount){
Row row = sheet.getRow(1);
if (moduleCount==0) {}
if (moduleCount>0) {row.createCell(2).setCellValue(moduleCount.toString());}
}
}
Now i use 2 files, because i need to save my formulas. I want to use only 1 (source) and update it correctly.

Categories