Saturday, August 31, 2013

Reading the Data from Excel File and Writing Data to an Excel File

package com.epis.dao;

import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;




public class ReadingExcelbackUp2 {
   
    ResultSet rs = null;
    //Log log = new Log(ReadingIncomeTaxExcelData.class);
    public static Connection getConnection(String airport)
    {
        Connection con=null;
        try{
            Class.forName("oracle.jdbc.driver.OracleDriver");
            con=DriverManager.getConnection("jdbc:oracle:thin:@192.168.0.25:1521:AIMH",airport.trim(),airport.trim());
        }
        catch(Exception e)
        {
            System.out.println("the exception is"+e.toString());
        }
        return con;
    }


   public void importTaxExcelData(String file) throws Exception {
          System.out.println("Readingfinanceexceldata.importAdjustmentExcelData()");
       
          Workbook workbook=Workbook.getWorkbook(new File(file));
          Sheet sheet=workbook.getSheet(0);
          Cell[] row = null;
          File exlFile = new File("C:/write2.xls");
          WritableWorkbook writableWorkbook = Workbook.createWorkbook(exlFile);
          WritableSheet writableSheet = writableWorkbook.createSheet("Sheet1", 1);
          try{
              List al=new ArrayList();

                for(int j=1; j<sheet.getColumns(); j++) {   
                    int count=0;
                    for(int i=1; i < sheet.getRows()&& !(sheet.getRow(i)[0].getContents()).equals(""); i++) {
                        row=sheet.getRow(i);
                        try{
                            Connection con =getConnection(row[j].getContents());
                            Statement stmt=con.createStatement();
                            String selectQry=" SELECT OPERATOR_CD,OPERATOR_NAME,AGENCY_CD,UNIQUE_CD FROM Tc_Operator_Mt WHERE Upper(Trim(Operator_Name)) Like Upper(Trim('"+row[0].getContents().trim()+"%')) ";
                            System.out.println(" selectQry :"+selectQry);
                            ResultSet rs=stmt.executeQuery(selectQry);
                           
                            if(rs.next()) {
                                count++;   
                                System.out.println("Records Exist----------");
                                String cone=rs.getString(1);
                                String ctwo=rs.getString(2);
                                String cthree=rs.getString(3);
                                String cfour=rs.getString(4);
                               
                                al.add(cone+","+ctwo+","+cthree+","+cfour);
                               
                                System.out.println("cone   :"+cone);
                                System.out.println("ctwo   :"+ctwo);
                                System.out.println("cthree :"+cthree);
                                System.out.println("cfour  :"+cfour);
                               
                            }
                            if(rs!=null) rs.close();
                            if(stmt!=null) stmt.close();
                            if(con!=null) con.close();
                           
                               
                        }
                        catch(Exception e)
                        {
                            System.out.println("the exception is..."+e.toString());
                            e.printStackTrace();
                        }
                    }
                    System.out.println("count :"+count);
                }
                System.out.println(" list size : "+al.size());
                for(int ii=0;ii<al.size();ii++) {
                    StringTokenizer st=new StringTokenizer(al.get(ii).toString(),",");
                    while(st.hasMoreTokens()) {
                        String val1=st.nextToken();
                        String val2=st.nextToken();
                        String val3=st.nextToken();
                        String val4=st.nextToken();
                        writableSheet.addCell(new jxl.write.Label(1, ii, val1));
                        writableSheet.addCell(new jxl.write.Label(2, ii, val2));
                        writableSheet.addCell(new jxl.write.Label(3, ii, val3));
                        writableSheet.addCell(new jxl.write.Label(4, ii, val4));
                        System.out.println(" ii df : "+ii);
                    }
                }
                writableWorkbook.write();
//                writableWorkbook.write();*/
                writableWorkbook.close();
               
                    System.out.println("OVER----MODSALHEADFROMEXCEL---");
                    //con.commit();
               

          }
          catch(Exception e)
          {
            e.printStackTrace();
            }     
           }
            public static void main(String[] args) throws  Exception {
               
                ReadingExcelbackUp2 excel=new ReadingExcelbackUp2();
                try {
                    String fileName="D:/EXCELCB/Book2.xls";
                    excel.importTaxExcelData(fileName);
                }catch (Exception e) {
                     throw new Exception(e.getMessage());
                }
            }
       }

Reading the Data from Excel File and Writing Data to an Excel File

package com.epis.dao;

import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;




public class ReadingExcelbackUp2 {
   
    ResultSet rs = null;
    //Log log = new Log(ReadingIncomeTaxExcelData.class);
    public static Connection getConnection(String airport)
    {
        Connection con=null;
        try{
            Class.forName("oracle.jdbc.driver.OracleDriver");
            con=DriverManager.getConnection("jdbc:oracle:thin:@192.168.0.25:1521:AIMH",airport.trim(),airport.trim());
        }
        catch(Exception e)
        {
            System.out.println("the exception is"+e.toString());
        }
        return con;
    }


   public void importTaxExcelData(String file) throws Exception {
          System.out.println("Readingfinanceexceldata.importAdjustmentExcelData()");
       
          Workbook workbook=Workbook.getWorkbook(new File(file));
          Sheet sheet=workbook.getSheet(0);
          Cell[] row = null;
          File exlFile = new File("C:/write2.xls");
          WritableWorkbook writableWorkbook = Workbook.createWorkbook(exlFile);
          WritableSheet writableSheet = writableWorkbook.createSheet("Sheet1", 1);
          try{
              List al=new ArrayList();

                for(int j=1; j<sheet.getColumns(); j++) {   
                    int count=0;
                    for(int i=1; i < sheet.getRows()&& !(sheet.getRow(i)[0].getContents()).equals(""); i++) {
                        row=sheet.getRow(i);
                        try{
                            Connection con =getConnection(row[j].getContents());
                            Statement stmt=con.createStatement();
                            String selectQry=" SELECT OPERATOR_CD,OPERATOR_NAME,AGENCY_CD,UNIQUE_CD FROM Tc_Operator_Mt WHERE Upper(Trim(Operator_Name)) Like Upper(Trim('"+row[0].getContents().trim()+"%')) ";
                            System.out.println(" selectQry :"+selectQry);
                            ResultSet rs=stmt.executeQuery(selectQry);
                           
                            if(rs.next()) {
                                count++;   
                                System.out.println("Records Exist----------");
                                String cone=rs.getString(1);
                                String ctwo=rs.getString(2);
                                String cthree=rs.getString(3);
                                String cfour=rs.getString(4);
                               
                                al.add(cone+","+ctwo+","+cthree+","+cfour);
                               
                                System.out.println("cone   :"+cone);
                                System.out.println("ctwo   :"+ctwo);
                                System.out.println("cthree :"+cthree);
                                System.out.println("cfour  :"+cfour);
                               
                            }
                            if(rs!=null) rs.close();
                            if(stmt!=null) stmt.close();
                            if(con!=null) con.close();
                           
                               
                        }
                        catch(Exception e)
                        {
                            System.out.println("the exception is..."+e.toString());
                            e.printStackTrace();
                        }
                    }
                    System.out.println("count :"+count);
                }
                System.out.println(" list size : "+al.size());
                for(int ii=0;ii<al.size();ii++) {
                    StringTokenizer st=new StringTokenizer(al.get(ii).toString(),",");
                    while(st.hasMoreTokens()) {
                        String val1=st.nextToken();
                        String val2=st.nextToken();
                        String val3=st.nextToken();
                        String val4=st.nextToken();
                        writableSheet.addCell(new jxl.write.Label(1, ii, val1));
                        writableSheet.addCell(new jxl.write.Label(2, ii, val2));
                        writableSheet.addCell(new jxl.write.Label(3, ii, val3));
                        writableSheet.addCell(new jxl.write.Label(4, ii, val4));
                        System.out.println(" ii df : "+ii);
                    }
                }
                writableWorkbook.write();
//                writableWorkbook.write();*/
                writableWorkbook.close();
               
                    System.out.println("OVER----MODSALHEADFROMEXCEL---");
                    //con.commit();
               

          }
          catch(Exception e)
          {
            e.printStackTrace();
            }     
           }
            public static void main(String[] args) throws  Exception {
               
                ReadingExcelbackUp2 excel=new ReadingExcelbackUp2();
                try {
                    String fileName="D:/EXCELCB/Book2.xls";
                    excel.importTaxExcelData(fileName);
                }catch (Exception e) {
                     throw new Exception(e.getMessage());
                }
            }
       }

Monday, June 10, 2013

getCurrentDate in Java

    public String getCurrentDate(String format) {
        String date = "";
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        date = sdf.format(new Date());
        return date;
    }

RemDupFromList.java

RemDupFromList.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package java4s;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
public class RemDupFromList {
    public static void main(String[] args)
    {
        List li = new ArrayList();
              li.add("one");
              li.add("two");
              li.add("three");
              li.add("one");//Duplicate
              li.add("one");//Duplicate
             // We have facility to pass a List into Set constructor and vice verse to cast     
                List li2 = new ArrayList(new HashSet(li)); //no order
             // List li2 = new ArrayList(new LinkedHashSet(li)); //If you need to preserve the order use 'LinkedHashSet'
             Iterator it= li2.iterator();
             while(it.hasNext())
             {
                 System.out.println(it.next());
             }
    }
}

Explanation

  • Take your normal List object
  • Pass that List li object to Set [Line number 22]  => So finally we have Set object in our hand, just pass this current Set object as argument to ArrayList, so we got new List object li2 without duplicate
  • But if you would like to preserve the order of data use LinkedHashSet rather HashSet

How to find duplicate values in ArrayList with out iterarting..?

  1. List list = new ArrayList();  
  2.     list.add("a");  
  3.     list.add("a");  
  4.     list.add("b");  
  5.     list.add("c");  
  6.     list.add("c");   
  7.     System.out.println(list);  
  8.     Set s = new HashSet(list);  
  9.     System.out.println("Set :- " +s); 

findDuplicates in a list and return them

public Set<Integer> findDuplicates(List<Integer> listContainingDuplicates)
{ 
  final Set<Integer> setToReturn = new HashSet(); 
  final Set<Integer> set1 = new HashSet();

  for (Integer yourInt : listContainingDuplicates)
  {
   if (!set1.add(yourInt))
   {
    setToReturn.add(yourInt);
   }
  }
  return setToReturn;
}
 
 have a List of type Integer eg:

[1, 1, 2, 3, 3, 3]

I would like a method to return all the duplicates eg:
[1, 3]
 
 ----------------
 
List<Item> list = ...;
list.removeAll(new HashSet<Item>(list));
return new HashSet<Item>(list); 
  ----------------
public static Set<Integer> findDuplicates(List<Integer> input) {
    List<Integer> copy = new ArrayList<Integer>(input);
    for (Integer value : new HashSet<Integer>(input)) {
        copy.remove(value);
    }
    return new HashSet<Integer>(copy );
} 
 ----------------
public static void main(String[] args) {
        List<Integer> list = new LinkedList<Integer>();
        list.add(1);
        list.add(1);
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(3);
        Map<Integer,Integer> map = new HashMap<Integer, Integer>();
        for (Integer x : list) { 
            Integer val = map.get(x);
            if (val == null) { 
                map.put(x,1);
            } else {
                map.remove(x);
                map.put(x,val+1);
            }
        }
        List<Integer> result = new LinkedList<Integer>();
        for (Entry<Integer, Integer> entry : map.entrySet()) {
            if (entry.getValue() > 1) {
                result.add(entry.getKey());
            }
        }
        for (Integer x : result) { 
            System.out.println(x);
        }

    } 
 ----------------
public void testFindDuplicates() {

    List<Integer> list = new ArrayList<Integer>();
    list.add(1);
    list.add(1);
    list.add(2);
    list.add(3);
    list.add(3);
    list.add(3);

    Set<Integer> result = new HashSet<Integer>();
    int currentIndex = 0;
    for (Integer i : list) {
        if (!result.contains(i) && list.subList(currentIndex + 1, list.size()).contains(i)) {
            result.add(i);
        }
        currentIndex++;
    }
    assertEquals(2, result.size());
    assertTrue(result.contains(1));
    assertTrue(result.contains(3));
}
-----------
ublic List<int> GetDuplicates(int max)
{   
    //allocate and clear memory to 0/false
    bit[] buckets=new bit[max]
    memcpy(buckets,0,max);
    //find duplicates
    List<int> result=new List<int>();
    foreach(int val in List)
    {
        if (buckets[val])
        {
            result.add(value);
        }
        else
        {
            buckets[val]=1;
        }
    }
    return  result
}  
----------
private <T> Set<T> findDuplicates(Collection<T> list) {

    Set<T> duplicates = new LinkedHashSet<T>();
    Set<T> uniques = new HashSet<T>();

    for(T t : list) {
        if(!uniques.add(t)) {
            duplicates.add(t);
        }
    }

    return duplicates;
}
-------
 
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
 
public class CrunchifyFindDuplicateInList {
 
    /**
     * @author Crunchify.com
     */
 
    public static void main(String[] args) {
        List<String> list = new LinkedList<String>();
        for (int i = 0; i < 10; i++) {
            list.add(String.valueOf(i));
        }
        for (int i = 0; i < 5; i++) {
            list.add(String.valueOf(i));
        }
 
        System.out.println("My List : " + list);
        System.out.println("\nHere are the duplicate elements from list : " + findDuplicates(list));
    }
 
    public static Set<String> findDuplicates(List<String> listContainingDuplicates) {
 
        final Set<String> setToReturn = new HashSet<String>();
        final Set<String> set1 = new HashSet<String>();
 
        for (String yourInt : listContainingDuplicates) {
            if (!set1.add(yourInt)) {
                setToReturn.add(yourInt);
            }
        }
        return setToReturn;
    }
}
Output
1
2
3
My List : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4]
 
Here are the duplicate elements from list : [3, 2, 1, 0, 4]