Drop Down

Showing posts with label Bakchodi. Show all posts
Showing posts with label Bakchodi. Show all posts

Sunday, January 12, 2020

Get All Methods of Objects Class

package warmUP;

import java.lang.reflect.Method;

public class Show_Methods {

public static void main(String[] args) throws ClassNotFoundException
{
int count = 0;
Class c = Class.forName("java.lang.Object");
Method[] m = c.getDeclaredMethods();
for(Method m1 : m)
{
count++;
System.out.println(m1.getName());
}
System.out.println("Total No. of Methods: "+count);
}

}
----------------------------------------------------------------
OutPut:
---------
finalize
wait
wait
wait
equals
toString
hashCode
getClass
clone
notify
notifyAll
registerNatives
Total No. of Methods: 12


Sunday, October 6, 2019

Send Free SMS using Java code

package freesms;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

public class SendSMS
{

public static void main(String[] args)
{
try {
// Construct data
String apiKey = "apikey=" + "2D5i+ah7Dtw-6Ggu4kukZUJrnHddMJLXjNvFGstF3A"; // only 10 credits left
String message = "&message=" + "This is your message";
String sender = "&sender=" + "TXTLCL"; //not to be changed
String numbers = "&numbers=" + "8744973456";

// Send data
HttpURLConnection conn = (HttpURLConnection) new URL("https://api.textlocal.in/send/?").openConnection();
String data = apiKey + numbers + message + sender;
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Length", Integer.toString(data.length()));
conn.getOutputStream().write(data.getBytes("UTF-8"));
final BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
final StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = rd.readLine()) != null)
{
stringBuffer.append(line);
System.out.println(">>> "+stringBuffer);

}
rd.close();

//return stringBuffer.toString();

  }
catch (Exception e)
{
System.out.println("Error SMS " + e);
//return "Error " + e;
}

}

}
==================================================
---------
 NOTE
---------
Website :  https://control.textlocal.in/settings/apikeys/
id: amitin2015@gmail.com
P/W: S****g***19
===================================================

Saturday, September 21, 2019

Code to Move log dump to another location

package com.amit.model;

import java.io.File;
import java.io.FileInputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

public class ScanToMoveFolder
{
static File source1 = null;
static File dest1 = null;
public static void main(String[] args)
{
//***************************READING PROPERTIES FILE*****************
try
{
  FileInputStream ip = new FileInputStream("config.properties");
  Properties prop = new Properties();
  prop.load(ip);
  source1 = new File(prop.getProperty("fromPath_1"));
  dest1 = new File(prop.getProperty("toPath_1"));
 
  ProcessData p1 = new ProcessData();
  Thread t1 = new Thread(p1);
  t1.start();  
 
}
catch(Exception e)
{
e.printStackTrace();
}

}


}



=====================================================================

package com.amit.model;

import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.io.FileUtils;

public class ProcessData implements Runnable
{
private boolean keepRunning = true;
private File source1 = ScanToMoveFolder.source1;
private File dest1 = ScanToMoveFolder.dest1;
ProcessData pro;
public String timestamp = null;
public void stop()
{
keepRunning = false;
}
private  String gettime()
{
DateFormat dateFormat = new SimpleDateFormat("dd-M-yyyy");
Date date = new Date();
return dateFormat.format(date);
}
private  String getDatetime()
{
DateFormat dateFormat = new SimpleDateFormat("dd-M-yyyy hh:mm:ss");
Date date = new Date();
return dateFormat.format(date);
}

public void run()
{
while(keepRunning)
{
try
{
timestamp = gettime();
System.out.println("TIMESTAMP::>> "+timestamp);
copyFolder(source1,dest1);
deleteFiles(source1);
System.out.println("*********************************************************");
System.out.println("************UTILITY IS SLEEPING FOR  24 HR***************");
System.out.println("*********************************************************");
System.out.println("*****Utility started to sleep at :"+getDatetime()+"******");
System.out.println("*********************************************************");
Thread.sleep(1000*60*60*24);
}
catch(Exception e)
{
e.printStackTrace();
}
}

}

private void copyFolder(File sourceFolder, File destinationFolder)
{
try
{
System.out.println("source folder "+sourceFolder);
System.out.println("destination folder "+destinationFolder);
if(sourceFolder.isDirectory())
{
if(!destinationFolder.exists())
{
destinationFolder.mkdir();
System.out.println("Directory Created :: "+destinationFolder);
}
String path = check_if_leaf_directory(sourceFolder,destinationFolder); //$$$$$$$$$$$$$$$$$$$$$$$$
System.out.println("Path::"+path);
File path_file = new File(path);
destinationFolder = path_file;
String files[] = sourceFolder.list();
for(String file : files)
{
//boolean dir_flag = false;
File srcFile = new File(sourceFolder,file);
File destFile = new File(destinationFolder,file);
copyFolder(srcFile,destFile);
}
}
else
{
//Files.copy(sourceFolder.toPath(), destinationFolder.toPath(), StandardCopyOption.REPLACE_EXISTING); //---> for java 7 and above
FileUtils.copyFile(sourceFolder, destinationFolder);  //----> for java 1.6 and lower
System.out.println("File copied :: "+destinationFolder);
}

}
catch(Exception e)
{
e.printStackTrace();
}

}

private String check_if_leaf_directory(File dir, File destination)
{
String path = destination.toString();
System.out.println("path********* "+path);
try
{
File[] files = dir.listFiles();
for(File file : files)
{
if(!file.isDirectory())
{
String destination_appended_path_str = (destination + File.separator +timestamp);
File destination_appended_path_file = new File(destination_appended_path_str);
destination_appended_path_file.mkdir();

path = destination_appended_path_file.toString();
System.out.println("<<path>>"+path);
}
else
{

}

}

}
catch(Exception e)
{
e.printStackTrace();
}
return path;
}
private void deleteFiles(File dir)
{
try
{
  File[] files = dir.listFiles();
  for(File file1 : files)
  {
  if(file1.isDirectory())
  {
  System.out.println("Directory: "+file1.getCanonicalPath());
  deleteFiles(file1);
  }
  else
  {
  file1.delete();
  System.out.println("inside else..."+file1.getAbsolutePath());
  }
 
  }
}
catch(Exception e)
{
e.printStackTrace();
}

}

}



============================config.properties==========================

fromPath_1 = D:\\\\work\\TestEnv\\source
toPath_1 = D:\\\\work\\TestEnv\\destination







Wednesday, June 5, 2019

Create Excel :- Header/color/columns etc...

package Excel_create_style;

import org.apache.poi.*;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.PatternFormatting;

import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

public class Test2 {

public static void main(String[] args)
{
  //Workbook workbook = new XSSFWorkbook();
  Workbook workbook = new HSSFWorkbook();  
  Sheet sheet1 = workbook.createSheet("sheet1");
  Sheet sheet2 = workbook.createSheet("sheet 2");
  HSSFRow row;
 
  Row header = (HSSFRow) sheet1.createRow(0);
  sheet1.addMergedRegion(new CellRangeAddress(0,0,1,7)); //--Merge
  header.createCell(1).setCellValue("Output Structure"); //
  //Heder style
  Font font_h = workbook.createFont();
  font_h.setBold(true);
  font_h.setFontHeightInPoints((short)12);
  CellStyle Styleheader = workbook.createCellStyle();
  Styleheader.setAlignment(HorizontalAlignment.CENTER);  
  Styleheader.setFont(font_h);
  Styleheader.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
  Styleheader.setFillPattern(FillPatternType.SOLID_FOREGROUND);
 
  header.getCell(1).setCellStyle(Styleheader);
 
  //************************************
 
     
  //************************************
 
  //--- Row 2 me ye headers aaega
  row = (HSSFRow) sheet1.createRow(2);
  row.setHeight((short) 500);

  row.createCell(1).setCellValue("Segment");
  row.createCell(2).setCellValue("Region");
  row.createCell(3).setCellValue("Borrower Name");
  row.createCell(4).setCellValue("RM Name");
  row.createCell(5).setCellValue("Date Full Information received");
  row.createCell(6).setCellValue("Date Letter Issued");
  row.createCell(7).setCellValue("Date RM Letter Requested");
 
 
  //---
  //----Font Formatting
 
  for(int i =1;i<=7;i++) {
  CellStyle stylerowHeading = workbook.createCellStyle();
  Font font = workbook.createFont();
  font.setBold(true);
  font.setFontHeightInPoints((short)10);
  stylerowHeading.setFont(font);
  stylerowHeading.setAlignment(HorizontalAlignment.CENTER);
  stylerowHeading.setVerticalAlignment(VerticalAlignment.CENTER);
  stylerowHeading.setFillForegroundColor(IndexedColors.TURQUOISE.getIndex());
  stylerowHeading.setFillPattern(FillPatternType.SOLID_FOREGROUND);
 
  stylerowHeading.setBorderLeft(BorderStyle.MEDIUM);
  stylerowHeading.setBorderRight(BorderStyle.MEDIUM);
  stylerowHeading.setBorderTop(BorderStyle.MEDIUM);
  stylerowHeading.setBorderBottom(BorderStyle.MEDIUM);
 
  row.getCell(i).setCellStyle(stylerowHeading);
  }
 
  //------Auto Fit
  for(int i =1;i<=7;i++)
  {
  sheet1.autoSizeColumn(i);
  }
 
 
  //*****************
  //CellStyle dynamic_rows = workbook.createCellStyle();
  //dynamic_rows.setBorderLeft(BorderStyle.THIN);
  //dynamic_rows.setBorderRight(BorderStyle.THIN);
  //dynamic_rows.setBorderBottom(BorderStyle.THIN);
 
  //******************
 
  String[] rowVal = new String[7];
  insertrowVal(rowVal);  
  Map < String, String[]> m = new LinkedHashMap < String, String[] >();
  //m.put( "1", rowVal);
  m.put( "1", rowVal);
  m.put( "2", rowVal);
  m.put( "3", rowVal);
  m.put( "4", rowVal);
  m.put( "5", rowVal);
   
//Iterate over data and write to sheet
      Set <String> keyid = m.keySet();
      int rowid = 3;

      for (String key : keyid) {
    row = (HSSFRow) sheet1.createRow(rowid++);
         String [] str = m.get(key);
         int cellid = 1;
     
         for (String obj : str)
         {
        //row.getCell(cellid).setCellStyle(dynamic_rows);
            Cell cell = row.createCell(cellid++);
            cell.setCellValue((String)obj);
           
         }
      }
     
  try
  {
  FileOutputStream output = new FileOutputStream("D:\\work\\newgen2.xls");
  workbook.write(output);
  output.close();
  System.out.println("File created ....");

  }
  catch(Exception e)
  {
  e.printStackTrace();
  }
 
 
}

private static void insertrowVal(String[] rowVal)
{
rowVal[0]="apple";
rowVal[1]="Orange";
rowVal[2]="Banana";
rowVal[3]="Mango";
rowVal[4]="Papaya";
rowVal[5]="Lichy";
rowVal[6]="Grapes";

}

}

----------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------
JARS :- poi-bin-4.1.0-20190412.tar





Monday, April 22, 2019

Cannot get a STRING value from a NUMERIC cell. How can I resolve this issue in selenium webdriver using POI?

Exception in thread "main" java.lang.IllegalStateException: Cannot get a STRING value from a NUMERIC cell
at org.apache.poi.xssf.usermodel.XSSFCell.typeMismatch(XSSFCell.java:1003)
at org.apache.poi.xssf.usermodel.XSSFCell.getRichStringCellValue(XSSFCell.java:389)
at org.apache.poi.xssf.usermodel.XSSFCell.getStringCellValue(XSSFCell.java:341)
at upload_download_Excel_DB.ProcessData.main(ProcessData.java:42)
==========================================================




This exception is occurred when code try to read Numeric value as string. Apache POI will not convert from Numeric to String.

There are two solution :

1. First convert cell type to string and Read it. Please check below code :
import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.util.Locale;

    import org.apache.poi.ss.usermodel.Cell;
    import org.apache.poi.ss.usermodel.DataFormatter;
    import org.apache.poi.xssf.usermodel.XSSFSheet;
    import org.apache.poi.xssf.usermodel.XSSFWorkbook;

    public class ReadExcel {

    public static void main(String[] args) throws Exception {
        File src=new File("C:\\Users\\Sagar\\Desktop\\TestInputData.xlsx");

        FileInputStream fis=new FileInputStream(src);

        XSSFWorkbook wb=new XSSFWorkbook(fis);

        XSSFSheet sheet1=wb.getSheetAt(0);
        int rowcount=sheet1.getLastRowNum();
        System.out.println("Total Row" + rowcount);

        for(int i=0;i<rowcount+1;i++) {

            System.out.println(i);
            //GET CELL
            Cell cell1 = sheet1.getRow(i).getCell(0);   
            //SET AS STRING TYPE
            cell1.setCellType(Cell.CELL_TYPE_STRING);
            String data0= cell1.getStringCellValue();
            System.out.println("Test Data From Excel : "+data0);
        }

        wb.close();
      }
    }

2. Get type first and print by its option. Please see the code:
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.util.Locale;

    import org.apache.poi.ss.usermodel.Cell;
    import org.apache.poi.ss.usermodel.DataFormatter;
    import org.apache.poi.ss.usermodel.DateUtil;
    import org.apache.poi.xssf.usermodel.XSSFSheet;
    import org.apache.poi.xssf.usermodel.XSSFWorkbook;

    public class ReadExcel {

    public static void main(String[] args) throws Exception {
        File src=new File("C:\\Users\\Sagar\\Desktop\\TestInputData.xlsx");

        FileInputStream fis=new FileInputStream(src);

        XSSFWorkbook wb=new XSSFWorkbook(fis);

        XSSFSheet sheet1=wb.getSheetAt(0);
        int rowcount=sheet1.getLastRowNum();
        System.out.println("Total Row " + rowcount);

        for(int i=0;i<rowcount+1;i++) {


            Cell cell1 = sheet1.getRow(i).getCell(0);   

            switch (cell1.getCellType()) {

            case Cell.CELL_TYPE_STRING:
                System.out.println(cell1.getRichStringCellValue().getString());
                break;

            case Cell.CELL_TYPE_NUMERIC:
                if (DateUtil.isCellDateFormatted(cell1)) {
                    System.out.println(cell1.getDateCellValue());
                } else {
                    System.out.println(cell1.getNumericCellValue());
                }
                break;

            case Cell.CELL_TYPE_BOOLEAN:
                System.out.println(cell1.getBooleanCellValue());
                break;

            case Cell.CELL_TYPE_FORMULA:
                System.out.println(cell1.getCellFormula());
                break;

            default:
                System.out.println();
        }

            //String data0= cell1.getStringCellValue();
            //System.out.println("Test Data From Excel : "+data0);
        }

        wb.close();


    }

    }

Thursday, April 11, 2019

Create & Read XML File


===========================Read_XML =============================
package XML_Parsing;

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Read_XML {

public static void main(String[] args) throws ParserConfigurationException 
{
  File xmlfile = new File("D:\\work\\Java Work Space\\files\\dummy.xml");
  
  DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
  DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
  Document document = documentBuilder.newDocument();
  
  document.getDocumentElement().normalize();
  
  NodeList list = document.getElementsByTagName("Developer");
  for(int i =0;i<list.getLength();i++)
  {
  Node node = list.item(i);
  
  if(node.getNodeType() == Node.ELEMENT_NODE)
  {
  Element element = (Element) node;
  
  System.out.println("ID: "+element.getAttribute("id"));
  System.out.println("Name: "+element.getElementsByTagName("Name").item(0).getTextContent());
  System.out.println("SurName: "+element.getElementsByTagName("Surname").item(0).getTextContent());
  }
  }

}

}

===========================Create_XML ===============================

package XML_Parsing;

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;


public class Create_XML {

public static void main(String[] args) throws ParserConfigurationException, TransformerException 
{
  DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
  DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
  
  Document document = documentBuilder.newDocument();
  Element element = document.createElement("Developer");
  
  Attr attr = document.createAttribute("Id");
  attr.setValue("1");
  element.setAttributeNode(attr);
  
  Element name = document.createElement("Name");
  name.appendChild(document.createTextNode("Amit"));
  element.appendChild(name);
  
  Element surname = document.createElement("surname");
  surname.appendChild(document.createTextNode("Manjhi"));
  element.appendChild(surname);
  
  Element hobby = document.createElement("hobby");
  hobby.appendChild(document.createTextNode("Coding"));
  element.appendChild(hobby);
  
  Element color = document.createElement("color");
  color.appendChild(document.createTextNode("yellow"));
  element.appendChild(color);
  
  TransformerFactory transformerfactory = TransformerFactory.newInstance();
  Transformer transformer = transformerfactory.newTransformer();
  DOMSource  source = new DOMSource(document);
  
  StreamResult streamresult = new StreamResult(new File("D:\\work\\Java Work Space\\files\\demo2.xml"));
  transformer.transform(source, streamresult);
  System.out.println("DONE.....................");
}

}

===========================ReadXMLFile ============================
package XML_Parsing;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;

public class ReadXMLFile {

  public static void main(String argv[]) {

    try {

File fXmlFile = new File("D:\\work\\Java Work Space\\files\\demo1.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();

System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("staff");
System.out.println("----------------------------");

for (int temp = 0; temp < nList.getLength(); temp++) {

Node nNode = nList.item(temp);
System.out.println("\nCurrent Element :" + nNode.getNodeName());
if (nNode.getNodeType() == Node.ELEMENT_NODE) {

Element eElement = (Element) nNode;

System.out.println("Staff id : " + eElement.getAttribute("id"));
System.out.println("First Name : " + eElement.getElementsByTagName("firstname").item(0).getTextContent());
System.out.println("Last Name : " + eElement.getElementsByTagName("lastname").item(0).getTextContent());
System.out.println("Nick Name : " + eElement.getElementsByTagName("nickname").item(0).getTextContent());
System.out.println("Salary : " + eElement.getElementsByTagName("salary").item(0).getTextContent());

}
}
    } catch (Exception e) {
e.printStackTrace();
    }
  }

}

Tuesday, April 9, 2019

Socket Programming : Client Server Communication

==============================CLIENT============================


import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;

public class Client {

public static void main(String[] args) throws Exception
{
String ip = "localhost";
int port = 6666;
Socket s = new Socket(ip,port);

String str = "Apples are good";
OutputStreamWriter os = new OutputStreamWriter(s.getOutputStream());
//PrintWriter out = new PrintWriter(os);
os.write(str);
os.flush();
//out.close();
s.close();
}

}

===================================SERVER===========================
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {

public static void main(String[] args) throws IOException 
{
  System.out.println("Server is Started...");
  ServerSocket ss = new ServerSocket(6666);
  
  System.out.println("Server is Waiting...");
  Socket s = ss.accept();
  
  System.out.println("Client Connected");
  BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
  String str1 = br.readLine();
  
  System.out.println("Client Data : "+str1);
  
}

}
======================================================================

Exel data to DataBase Using JDBC

package upload_download_Excel_Bakchodi;

import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFFactory;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class Excel_To_DB

{

public static void main(String[] args) {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl", "hr", "hr");
Statement st = con.createStatement();

con.setAutoCommit(false);
PreparedStatement pstm = null;
FileInputStream fis = new FileInputStream("D:\\work\\Java Work Space\\files\\demo.xlsx");

XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet sheet = wb.getSheetAt(0);
Row row;

for(int i=1; i<=sheet.getLastRowNum(); i++)
{
row = sheet.getRow(i);

String name = row.getCell(0).getStringCellValue();
String city = row.getCell(1).getStringCellValue();
String hobby = row.getCell(2).getStringCellValue();
String food = row.getCell(3).getStringCellValue();
String id = row.getCell(4).getStringCellValue();
String country  = row.getCell(5).getStringCellValue();

System.out.println(name+" : "+city+" : "+hobby+" : "+food+" : "+id+" : "+country);

String query = "insert into myexel values(?,?,?,?,?,?)";
PreparedStatement ps = con.prepareStatement(query);
ps.setString(1, name);
ps.setString(2, city);
ps.setString(3, hobby);
ps.setString(4, food);
ps.setString(5, id);
ps.setString(6, country);
int res = ps.executeUpdate();
if(res>0)
    System.out.println("Values inserted");
   
}
con.close();
/*
* XSSFFactory fs = new POIFSFileSystem( input ); XSSFWorkbook wb = new
* XSSFWorkbook(fs); XSSFSheet sheet = wb.getSheetAt(0); Row row;
*/
} catch (ClassNotFoundException e) {
System.out.println(e);
} catch (SQLException ex) {
System.out.println(ex);
} catch (IOException ioe) {
System.out.println(ioe);
}

}
}

==================TABLE==================

create table myexel( name varchar(20),
                    city varchar(20),
                    hobby varchar(20),
                    food varchar(20),
                    ID varchar(20),
                    Country varchar(20));
==========================================

Name city hobby food ID Country
amit Ranchi Football Fruits gdf USA
Sohan Jaiput hocky idly dfgd India
Mohan Mumbai golf litty dfgd Dubai
Mohan Mumbai golf litty dfgd England
Mohan Mumbai golf litty dfgd japan
===========================================













Read from Excel

package upload_download_Excel_Bakchodi;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class Excel_1
{
public static void main(String[] args) throws IOException
{
FileInputStream fis = new FileInputStream(new File("D:\\work\\Java Work Space\\files\\demo.xlsx"));

//create workbook instance that refers to .xls file
XSSFWorkbook wb = new XSSFWorkbook(fis);

//create sheet object to retrive sheet
XSSFSheet sheet = wb.getSheetAt(0);

//that is for evaluate the cell type
FormulaEvaluator formula = wb.getCreationHelper().createFormulaEvaluator();

for(Row row : sheet)
{
for(Cell cell : row)
{

switch(formula.evaluateInCell(cell).getCellType())
{
case STRING:
System.out.print(cell.getStringCellValue()+"\t\t");
break;
case NUMERIC:
System.out.print(cell.getNumericCellValue()+"\t\t");
break;
}

}
System.out.println();
}



}

}
========================================================================
Note : Download POI .Jars  from below link

Binary Distribution

Java 8 Notes Pics