Tuesday 17 November 2015

Display four square layout in andriod using linear layout.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="150dp">
    <LinearLayout android:orientation="horizontal" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="0.5">
        <ImageButton android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/imageButton71" android:layout_gravity="center_horizontal" android:src="@drawable/sadas" />
    </LinearLayout>
    <LinearLayout android:orientation="vertical" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="0.5">
        <LinearLayout android:orientation="horizontal" android:layout_width="wrap_content" android:layout_weight="1" android:layout_height="75dp">
            <LinearLayout android:orientation="horizontal" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="0.5">
                <ImageButton android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/imageButton1" android:layout_gravity="center_horizontal" android:src="@drawable/sadas" />
            </LinearLayout>
            <LinearLayout android:orientation="horizontal" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="0.5">
                <ImageButton android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/imageButton" android:src="@drawable/wreew" android:layout_gravity="center_horizontal" />
            </LinearLayout>
        </LinearLayout>
        <LinearLayout android:orientation="horizontal" android:layout_width="match_parent" android:layout_weight="1" android:layout_height="75dp">
            <LinearLayout android:orientation="horizontal" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="0.5">
                <ImageButton android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/imageButton21" android:layout_gravity="center_horizontal" android:src="@drawable/sadas" />
            </LinearLayout>
            <LinearLayout android:orientation="horizontal" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="0.5">
                <ImageButton android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/imageButton22" android:src="@drawable/wreew" android:layout_gravity="center_horizontal" />
            </LinearLayout>
        </LinearLayout>
    </LinearLayout>
</LinearLayout>

Friday 18 September 2015

ABSTRACT DATA TYPES (ADTS)


·         One of the basic rules concerning programming is that no routine should ever exceed a page. This is accomplished by breaking the program down into modules.
·         Each module is a logical unit and does a specific job. Its size is kept small by calling other modules.
·         Modularity has several advantages. First, it is much easier to debug small routines than large routines. Second, it is easier for several people to work on a modular program simultaneously. Third, a well-written modular program places certain dependencies in only one routine, making changes easier.
·         For instance, if output needs to be written in a certain format, it is certainly important to have one routine to do this.
·          If printing statements are scattered throughout the program, it will take considerably longer to make modifications.
·         The idea that global variables and side effects are bad is directly attributable to the idea that modularity is good.
·         An abstract data type (ADT) is a set of operations. Abstract data types are mathematical abstractions; nowhere in an ADT's definition is there any mention of how the set of operations is implemented. This can be viewed as an extension of  modular design.

·          Objects such as lists, sets, and graphs, along with their operations, can be viewed as abstract data types, just as integers, reals, and booleans are data types. Integers, reals, and booleans have operations associated with them, and so do abstract data types.
·         For the set ADT, there may be operations as union, intersection, size, and complement. Alternately, the two operations union and find, which would define a different ADT on the set.
·          The basic idea is that the implementation of these operations is written once in the program, and any other part of the program that needs to perform an operation on the ADT can do so by calling the appropriate function.

·         If for some reason implementation details need to change, it should be easy to do so by merely changing the routines that perform the ADT operations. This change, would be completely transparent to the rest of the program.

Wednesday 2 September 2015

Character to Number conversion algorithm


This blog explains about the algorithm which will explain about character to number conversion,

Given the character representation of an integer convert it to its conventional decimal format.
Algorithm development
            The difference between the character representation of an integer and its conventional number representation is to be known. The number of different characters needed to represent textual and string information is relatively small. The upper and lower case alphabetic characters, the ten digits, and various punctuation and control characters make up only about one hundred different characters.
In contrast to this, the range of different integers (and real numbers) that are needed may extend into the millions, the bil1ions and even further. To obtain unique representations for such a large span of numbers requires a considerable amount of "space" to store each individual number. Numbers are represented in the computer in binary positional notation using just the 0 and 1 digits. As an example, let us examine the binary and decimal positional representations for the decimal number 221.

Comparing the two representations for 221, only 3 decimal digits are needed to represent 221 whereas 8 binary digits are used. To represent one billion, we need 10 decimal digits and about 32 binary digits or bits. The fundamental unit or computer word size for storing numbers is usually one of 16,32,36,60 or 64 bits. since only 7 or 8 bits (8 bits are called a byte) are all that is needed to distinguish among the hundred or so characters that we are likely to need (i.e. 2M=256) it is therefore very wasteful of computer memory to store only one character in the basic storage unit for numbers.
The solution is therefore to pack several characters into each computer word. for example, on 32-bit computers we find that four 8-bit characters are usually stored in each computer word. To make this packing possible It has been necessary to assign fixed 8-bit codes to the one hundred or so characters. One of the most widely used of these coding systems is called the American Standard Code for Information Interchange or ascii code. Some examples from this system are shown in Table .
Note that the decimal digits ,'0, 1,2,3, ..., 9, a~ also assigned 8-bit character code values. Because of this it is convenient in many applications to represent numbers as sequences of character), For example, a date may be represented by a string of characters; for example,
                                                            23 April 1984
With representations like this there are times when it is necessary to do conventional arithmetic calculations on the numbers represented as sequences of 8-bit characters. In our example above the 23 does not have the value of 2 tens and 3 units but rather there are the decimal values.50 and 51 in successive8-bit bytes.
The arithmetic operations  cannot be done directly one character code representations because the corresponding binary representation does not conform to the standard binary positional notation used to represent numbers in the computer. . Our only alternative in such circumstances is to convert the number from its character representation to its conventional number internal representation. This brings us back to our original character-to-number conversion problem.
The task is therefore to accept as input a character representation of a number containing a known number of characters and make the conversion to the conventional decimal representation. To do this it will be necessary to use the knowledge of the particular character code being employed. In this example, we will choose to work with the ascii code. Fortunately, most programming languages including Pascal provide some additional functions to make tasks like this relatively straightforward to perform. To convert the four-character sequence, 1984 to the decimal number 1984. The representation start out with is,

To make the conversion, the 49 will need to be converted to 1000, the 57 to 900, the 56 to 80 and the 52 to 4 units. To get the appropriate decimal digit in each case we have had to subtract 48 (the ascii value of character 0) from the ascii value of each character. Pascal makes this job easier by providing a function called word which accepts an 8-bit character as its argument and returns as output its corresponding decimal (in our case ascii) value, e.g. the statement.
                                                            x := ord(‘9’)
will assign to x the decimal value 57.
In our example, to get the decimal digits subtract ord(‘0’) from the ascii values of each of the characters in the sequence.
The next step is to use the digits to construct the corresponding decimal number. The character sequence will need to be processed one character at a time to obtain the decimal digits. What we must now work out is how each digit is to be converted to make its appropriate contribution to the decimal number we are seeking.
Start processing the characters from the left, when " 1" is encountered it is not immediately obvious what power of ten it should be multiplied by after the ascii conversion.
            However, by the time when a second character is encountered in the sequence, it should be multiplied by at least 10. And, at the time we have encountered the third character, we know the second digit should have been multiplied by 10 and the first digit multiplied by 100. That is, for our example of 1984,


All that is left now is to work out the details of the mechanism for implementing this process. The "shifting-to-the-left" mechanism can be obtained at each step by multiplying the previous decimal value by 10 and adding in the current decimal digit. Details of our implementation can now be outlined. It is assumed that the length of the character string has been determined and that a check has been made to confirm that the string represents a positive integer.
Algorithm description
  1. Establish the character string for, conversion to decimal and its length n.
  2. Initialize decimal vaJue to zero.
  3.  Set base0 value to the ascii or ordinal value of '0'.
  4.  While less than n characters have been examined do
(a) convert next character to corresponding decimal digit,
            (b) shift current decimal value to the left one digit and add in digit for current character,
      5. Return decimal integer corresponding to input character representation.

Tuesday 1 September 2015

Convert TWList object to xls


Do you want to convert BPM TWLIst object to excel file , here the code


import com.lombardisoftware.client.persistence.TWClass;
import com.lombardisoftware.data.twclass.TWClassDefinitionData;
import com.lombardisoftware.data.twclass.TWClassProperty;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import teamworks.TWList;
import teamworks.TWObject;

public class XlsxWriter {
    private SXSSFWorkbook workbook = new SXSSFWorkbook(100);

    public void createMultipleExcelFile(String path, TWObject object, TWList sheetNameList) throws ExcelWriterException {
        try {
            List<String> varList = this.getPropertyList(object);
            for (int i = 0; i < varList.size(); ++i) {
                TWList proertyValue = (TWList)object.getPropertyValue(varList.get(i));
                List<String> colModelList = this.getPropertyList((TWObject)proertyValue.getArrayData(0));
                this.addSheet(proertyValue, colModelList, sheetNameList.getArrayData(i).toString());
            }
            FileOutputStream output = new FileOutputStream(path);
            this.write(output);
            output.close();
        }
        catch (Exception e) {
            throw new ExcelWriterException(0, e.getMessage());
        }
    }

    public void createExcelFile(String path, TWList object, String sheetName) throws ExcelWriterException {
        try {
            ArrayList<String> colModelList = new ArrayList();
            TWObject report = (TWObject)object.getArrayData(0);
            colModelList = this.getPropertyList(report);
            this.addSheet(object, colModelList, sheetName);
            FileOutputStream output = new FileOutputStream(path);
            this.write(output);
            output.close();
        }
        catch (ParseException e) {
            throw new ExcelWriterException(0, e.getMessage());
        }
        catch (FileNotFoundException e) {
            throw new ExcelWriterException(0, e.getMessage());
        }
        catch (Exception e) {
            throw new ExcelWriterException(0, e.getMessage());
        }
    }

    private void addSheet(TWList data, List<String> colModel, String sheetName) throws ExcelWriterException {
        Sheet sheet = this.workbook.createSheet(sheetName);
        int numCols = colModel.size();
        int currentRow = 0;
        try {
            int i;
            Row row = sheet.createRow(currentRow);
            for (i = 0; i < numCols; ++i) {
                Cell cell = row.createCell(i);
                Font fn = this.workbook.createFont();
                fn.setBoldweight(700);
                CellStyle cs = this.workbook.createCellStyle();
                cs.setFont(fn);
                cell.setCellStyle(cs);
                cell.setCellValue(colModel.get(i).toString());
            }
            ++currentRow;
            for (i = 0; i < data.getArraySize(); ++i) {
                row = sheet.createRow(currentRow++);
                TWObject bean = (TWObject)data.getArrayData(i);
                for (int y = 0; y < numCols; ++y) {
                    Object proertyValue = bean.getPropertyValue(colModel.get(y));
                    String value = proertyValue != null ? proertyValue.toString() : "";
                    Cell cell = row.createCell(y);
                    cell.setCellValue(value);
                }
            }
            for (i = 0; i < numCols; ++i) {
                sheet.autoSizeColumn((int)((short)i));
            }
        }
        catch (Exception e) {
            throw new ExcelWriterException(0, e.getMessage());
        }
    }

    private void write(OutputStream outputStream) throws Exception {
        this.workbook.write(outputStream);
    }

    private List<String> getPropertyList(TWObject twObj) throws ExcelWriterException {
        ArrayList<String> variables = null;
        try {
            variables = new ArrayList<String>();
            List defnPropList = ((com.lombardisoftware.core.TWObject)twObj).getTWClass().getDefinition().getProperties();
            for (TWClassProperty prop : defnPropList) {
                variables.add(prop.getName());
            }
        }
        catch (Exception e) {
            throw new Exception(0, e.getMessage());
        }
        return variables;
    }
}

Reversing the digits of an Integer Algorithm


Design an algorithm that accepts a positive integer and reverses the order of its digits.

Algorithm development
Digit reversal is a technique that is sometimes used in computing to remove bias from a set of numbers. It is important in some fast information'-retrieval algorithms. A specific example clearly defines the relationship of the input to the desired output. For example,
                                                            Input: 27953
                                                            Output: 35972

The number 27953 is actually
2 * 10^4 + 7 * 10^3 + 9 * 10^2 + 5 * 10^1 + 3 * 10^0

To access the individual digits it is probably going to be easiest to start at one end of the number and work through to the other end. Because other than visually it is not easy to tell how many digits there are in the input number it will be best to try to establish the identity of the least significant digit (i.e. the rightmost digit). To do this we need to effectively "chop off" the least significant digit in the number. In other words we want to end up with 2795 with the 3 removed and identified.
The number 2795 can be obtained by integer division of the original number by 10 i.e. 27953 div 10->2795 This chops off the 3 but does not save it. However, 3 is the remainder that results from dividing 27953 by 10. To get this remainder use the mod function. That is,
                                                27953 mod 10->3
Applying the following two steps
            r := n mod 10  (l)=>(r = 3)
            n := n div 10    (2)=>(n = 2795)
the digit 3 is obtained and the new number 2795. Applying the same two steps to the new value of n we can obtain the 5 digit. Iteratively access the individual digits of the input number. Next major concern is to carry out the digit reversal. Applying digit extraction procedure to the first two digits  3 and then 5 are obtained. In the final output they appear as:
3 followed by 5
If the original number was 53 then we could obtain its reverse by first extracting the 3, multiplying it by 10, and then adding 5 to give 35. That is
                                                                        3x 10+5->35
The last three digits of the input number are 953. They appear in the "reversed" number as 359. Therefore at the stage when we have the 35 and then extract the 9 we can obtain the sequence 359 by multiplying 35 by 10 and adding 9. That is,

35 * 10 +9 -> 359
359 * 10 + 7 -> 3597
3597 * 10 + 2  ->  35972

The last number obtained from the multiplication and addition process Is the "digit-reversed" integer we have been seeking. On closely examining the digit extraction, and the reversal process, it is evident that they both involve a set of steps that can be performed iteratively.
            We must now find a mechanism for building up the "reversed" integer digit by digit. Let us assume that the variable dreverse is to be used to build the reversed integer. At each stage in building the reversed integer its previous value is used in conjunction with the most recently extracted digit. Rewriting the multiplication and addition process we have just described in terms of the variable dreverse,



Therefore to build the reversed integer we can use the construct:
            dreverse := (previous value of dreverse)* 10 + (most recently extracted rightmost digit)

The variable dreverse can be used on both sides of this expression. For the value of dreverse to be correct (i.e. dreverse = 3) after the first iteration it must initially be zero. This initialization step for dreverse is also needed to ensure that the algorithm functions correctly when the input number to be reversed is zero. Under what conditions should the iterative process terminate is to be found. The termination condition must in some way be related to the number of digits in the input integer. In fact as soon as all digits have been extracted and processed termination should apply. With each iteration the number of digits in the number being reversed is reduced by one, yielding the sequence shown in Table 2.1. Accumulative integer division of the "number being reversed" by 10 produces the sequence 27953, 95,279, ... . In our example, when the integer division process is applied for 5thtime a zero results since 2 is less than 10. Since at this point in the computation the "reversed" number has been fully constructed we can use the zero result to terminate the iterative process.

The central steps in our digit reversal algorithm are: 1. While there are still digits in the number being reversed do (a) extract the right most digit from the number being reversed and append this digit to the right-hand end of the current reversed number representation; (b) remove the rightmost digit from the number being reversed.

Algorithm description
1. Establish n, the positive integer to be reversed.
2. Set the initial condition for the reversed integer dreverse.
3. While the integer being reversed is greater than zero do
(a) use the remainder function to extract the rightmost digit of the 11 number being reversed; .
(b) increase the previous reversed integer representation dreverse by a factor of 10and add to it the most recently extracted digit to give the current dreverse value; .
(c) use integer division by 10 to remove the rightmost digit from the number being reversed.
This algorithm is most suitably implemented as a function which accepts as input the integer to be reversed and returns as output the integer with its digits reversed.

Monday 31 August 2015

Generation of the Fibonacci sequence

This blog explains about fibonacci sequence,

Generate and print the first~ terms of the Fibonacci sequence where n~ 1. The first few terms are
                                    0, 1, 2, 3, 5, 8, 13, ...

Each term beyond the first two is derived from the sum of its two nearest predecessors.

Algorithm development
From the definition: new term = preceding term- before preceding term. The last sentence of the problem statement suggests we may be able to use the definition to generate consecutive terms (apart from the first two) iteratively.
            Define:
                                    a as the term before the preceding term
                                    b as the preceding term
                                    c new term
            Then to start with:
                                    a:= 0    first fibonacci number
                                    b := 1  second Fibonacci number
                                    c := a+b  third Fibonacci number (from definition)
            When the new term c has been generated we have the third Fibonacci. To generate the fourth, or next Fibonacci number, we need to apply the same definition again. Before we can make this next computation we  need to make some adjustments. The fourth Fibonacci number is derived
From the sum of the second and third Fibonacci numbers. With regard to the definition the second Fibonacci number has the role of the term before the preceding term and the third Fibonacci number has the role of "the preceding term". Therefore ,before making the next (i.e. the fourth) computation we must ensure that:
            a) new term (i.e. the third) assumes the role of the preceding term,
            (b) and what is currently the preceding term must assume the role of the term before the   
                 preceding term.
            That is,
                        a:= 0                [1]        term before preceding term
                        b := 1              [2]        preceding term
                        c := a+b          [3]        new term
                        a:= b               [4]        term before preceding term becomes preceding term
                        b := c                [5]         preceding term becomes new term
After making step [5] we are in a position where we can use the definition to generate the next Fibonacci number. A way to do this is to loop back to step [3]. Further investigation of steps [3]->[5] indicates they can be placed in a loop to iteratively generate Fibonacci numbers (for n>2). The essential mechanism we could use is:
                                                a:= 0;
                                                b := 1;
                                                i:= 2;
                                                while i<n do
                                                begin
                                                            i:=i+l;
                                                            c := a+b;
                                                            a:= b;
                                                            b = c;
                                                end
As each new term c is Computed, the term before the preceding term, a, loses its relevance to the Calculation of the next Fibonacci number. To restore its relevance assignment is done. At all times only two numbers are relevant to the generation of the next Fibonacci number. In our computation, a third variable, c is introduced. Keep the two variables a and b always relevant. Because the first Fibonacci number becomes irrelevant as soon as the third Fibonacci is computed, start with:
                                                a:= 0;  [1]
                                                b := 1; [2]
                                                a := a+b [3]
Iterate on step [3] to generate successive Fibonacci numbers we run into trouble because we are not changing b. However, after step [3] we know the next (i.e. fourth) Fibonacci number can be generated using,
                                                next:=a+b;
Doing step [4], the old value of b, as defined by step [2], loses its relevance. To keep b  relevant at step [4] we can make the assignment:
                                                b := a+b
The first four steps then become
                                                a:= 0;              [1]
                                                b := 1;             [2]
                                                a := a+p;         [3]       
                                                b := a+b          [4]

After step [4]  find that a and b as defined are correct for generating the fifth Fibonacci number. At this point the old a value becomes irrelevant. Working through several more steps confirms that we can safely iterate on steps [3] and [4] to generate the required sequence. Because the algorithm generates Fibonacci numbers in pairs care must be taken to write out exactly n numbers. The easiest way to do this is to keep the output one step behind the generation phase. The complete algorithm description can now be given.



Algorithm description
1. Prompt and read n, the number of Fibonacci numbers to be generated.
2. Assign first two Fibonacci numbers a and b.
3. Initialize count of number generated.
4. While less than n Fibonacci numbers have been generated do
(a) write out next two Fibonacci numbers;
(b) generate next Fibonacci number keeping a relevant;
(c) generate next Fibonacci number from most recent pair keeping b relevant for next computation;
(d) update count of number of Fibonacci numbers generated, i.
5. If n even then write out last two Fibonacci numbers else write out second last Fibonacci number.

Saturday 29 August 2015

Factorial Computation

This blog will explain about factorial computation algorithm development step by step.

Algorithm development
Start the development of this algorithm by examining the definition of n!
                                    n!=1*2*3*….(n-1)*n for n>=1
                  
and by definition. Computer's arithmetic unit can only multiply two numbers at a time. Applying the factorial definition we get,
                                                           
                                                            0!= 1
                                                            1!=l x l
                                                            2!  1x 2
                                                            3!=l x 2 x 3
                                                            4! = l x 2 x 3 x 4
4! contains all the factors of 3L The only difference is the inclusion of the number 4. n! can always be obtained from (n-1)! by simply multiplying it by n (for n~ 1). That ~is, n! = nx(n-l)! for n.>=1

From step (2) onwards the same process is repeated. For the general (i+ 1)th step,
p:=p*i     (i+1)
This general step can be placed in a loop to iteratively generate n!. This allows to take advantage of the fact that the computer's arithmetic unit can only multiply two numbers at a time. In many ways this problem is very much like the problem of summing a set of n numbers. In the summation problem we performed a set of additions, whereas in this problem we need to generate a set of products. It follows from the general (i+ 1)th step that all factorials for n~ 1
can be generated iteratively. The instance where n = 0 is a special case which must be accounted for directly by the assignment
                                                p:= 1 (by definition of 0!)
The central part of the algorithm for computing n! therefore involves a special initial step followed by n iterative steps.
  1. Treat 0! as a special case (p := 1).
  2. Build each of the n remaining products p from its predecessor by an iterative process.
  3. Write out the value of n factorial.

Algorithm description
1. Establish n, the factorial required where n≥0.
2. Set product p for 0! (special case). Also set product count to zero.
3. While less than n products have been calculated repeatedly do
            (a) increment product count,
            (b) compute the ith product p by multiplying i by the most recent product.
4. Return the result n!.

This algorithm is most usefully implemented as a function that accepts as input a number n and returns as output the value of n! In the Pascal implementation p has been replaced by the variable factor.

Sample code for Factorial:
The below code will compute the factorial for 25.

for (c = 1; c <= 25; c++)
    fact = fact * c;
 
  printf("Factorial of %d = %d\n", n, fact);
 
Happy coding!!!!

Excel writer in java

My previous blog explained how to convert excel file to XMLor Json. Now Do you want to convert your JSON object to excel file. here you go....

Required jar same as excel reader. I have explained in my previous blog . Please check it.

Code for Excel Writer:

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.json.JSONArray;
import org.json.JSONObject;

/**
 * This class is used to create the excel file for the given list of TWObject in
 * the given file path.
 */
public class XlsxWriter {
private SXSSFWorkbook workbook;

/**
* A no-constructor argument is needed. This allows BPM to create an
* instance of this object when a method is invoked from BPM.
*/

public XlsxWriter() {
super();
workbook = new SXSSFWorkbook(100);
}

/**
* This method will handle the input from the calling application and
* creates the excel file for the given input.

* @param path
*            - Location where excel file should get create
* @param object
*            - List of TW object from BPM
* @param sheetName
*            - sheet name in the excel file.
* @throws ExcelWriterException
*/
public File createExcelFile(String path, String columns, String header,
String object) throws ExcelWriterException {

File newFile = null;
try {

List<String> colModelList = new ArrayList<String>();

JSONArray dataValue = new JSONArray(object);

// If the user didnt select any column, default table column order
// will be displayed
if (columns != null && !columns.equalsIgnoreCase("")) {
StringTokenizer colToken = new StringTokenizer(columns, ",");
while (colToken.hasMoreTokens()) {
colModelList.add(colToken.nextToken());
}
} else {
JSONArray columnList = new JSONArray(header);
for (int i = 0; i < columnList.length(); i++) {
colModelList.add(columnList.get(i).toString());
}
}

// Create a worksheet with given input values
addSheet(dataValue, colModelList, "WOAccrual_Report");

// Create an output stream to write the report to.
newFile = new File(path);
OutputStream output = new FileOutputStream(newFile);

// Write the report to the output stream
write(output);

// Finally, save the report
output.close();

} catch (ParseException e) {
System.out.println("");
} catch (FileNotFoundException e) {
System.out.println("");
} catch (Exception e) {
System.out.println("");
}
return newFile;
}

/**
* This method used to create a worksheet and add to workbook.

* @param data
*            - data to be inserted in to worksheet
* @param colModel
*            - This is used to provide the column name.
* @param sheetName
*            - work sheet name.
* @throws ExcelWriterException
*/
private void addSheet(JSONArray data, List<String> colModel,
String sheetName) throws ExcelWriterException {

Sheet sheet = workbook.createSheet(sheetName);
int numCols = colModel.size();
int currentRow = 0;
Row row;

try {

// Create the report header at row 0
row = sheet.createRow(currentRow);
// Loop over all the column beans and populate the report headers
for (int i = 0; i < numCols; i++) {
// Get the header text from the bean and write it to the cell
Cell cell = row.createCell(i);
Font fn = workbook.createFont();
fn.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);
CellStyle cs = workbook.createCellStyle();
cs.setFont(fn);
cell.setCellStyle(cs);
cell.setCellValue(colModel.get(i).toString());
}

currentRow++; // increment the spreadsheet row before we step into
// the data

// Write report rows
for (int i = 0; i < data.length(); i++) {
// create a row in the spreadsheet
row = sheet.createRow(currentRow++);
// get the bean for the current row
JSONObject bean = data.getJSONObject(i);

// For each column object, create a column on the current row based on the col model
for (int y = 0; y < numCols; y++) {
Object proertyValue = bean.getString(colModel.get(y));
String value;
if (proertyValue != null) {
value = proertyValue.toString();
} else {
value = "";
}
Cell cell = row.createCell(y);
cell.setCellValue(value);
}
}

// Autosize columns
for (int i = 0; i < numCols; i++) {
sheet.autoSizeColumn((short) i);
}

} catch (Exception e) {
throw new ExcelWriterException(0, e.getMessage());
}

}

/**
* This method will write the values into output stream.

* @param outputStream
* @throws Exception
*/
private void write(OutputStream outputStream) throws Exception {
workbook.write(outputStream);
}


}

Featured post

How to convert Java object to JSON or JSON to java object in java

Download Gson jar from this link  Quick Reference toJson() – Convert Java object to JSON Gson gson = new Gson ( ) ; <Java cla...