2012-12-28

Java Import Excel To Mysql Table

Import Excel to Mysql Table is easy using Apache POI , see previous post
Java Export Mysql Data To Excel , first add poi-3.7-20101029.jar and
mysql-connector-java to lib folder in your project.

file.xls Example
Id Name Address
1 Name 1 Address 1
2 Name 2 Address 2

This is code example

import java.io.FileInputStream;
import java.io.IOException;
import java.sql.DriverManager;
import java.sql.SQLException;

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 com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;


public class ImportData {

    /**
     * @param args
     */
    public static void main(String[] args) {
        try{
            Class.forName("com.mysql.jdbc.Driver");
            Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/test","root","");
            con.setAutoCommit(false);
            PreparedStatement pstm = null ;
            FileInputStream input = new FileInputStream("D://file.xls");
            POIFSFileSystem fs = new POIFSFileSystem( input );
            HSSFWorkbook wb = new HSSFWorkbook(fs);
            HSSFSheet sheet = wb.getSheetAt(0);
            Row row;
            for(int i=1; i<=sheet.getLastRowNum(); i++){
                row = sheet.getRow(i);
                int id = (int) row.getCell(0).getNumericCellValue();
                String name = row.getCell(1).getStringCellValue();
                String address = row.getCell(2).getStringCellValue();
                String sql = "INSERT INTO tablename VALUES('"+id+"','"+name+"','"+address+"')";
                pstm = (PreparedStatement) con.prepareStatement(sql);
                pstm.execute();
                System.out.println("Import rows "+i);
            }
            con.commit();
            pstm.close();
            con.close();
            input.close();
            System.out.println("Success import excel to mysql table");
        }catch(ClassNotFoundException e){
            System.out.println(e);
        }catch(SQLException ex){
            System.out.println(ex);
        }catch(IOException ioe){
            System.out.println(ioe);
        }

    }

}



Java Export Mysql Data To Excel          javareveal.blogspot.com
 

19 comments:

  1. Anonymous9:03 PM

    if some cell are empty i need to insert database column defalut value how can achive this pls hlp me

    ReplyDelete
  2. i am ashishkumar . i got an error like(cannot convert from HSSFRow to Row). please send a answer to my mail id (rt.ashish@gmail.com).

    ReplyDelete
    Replies
    1. import java.io.FileInputStream;
      import java.io.IOException;
      import java.sql.DriverManager;
      import java.sql.SQLException;

      import org.apache.poi.openxml4j.opc.OPCPackage;
      import org.apache.poi.poifs.filesystem.POIFSFileSystem;
      import org.apache.poi.ss.usermodel.Row;
      import org.apache.poi.xssf.usermodel.XSSFSheet;
      import org.apache.poi.xssf.usermodel.XSSFWorkbook;

      import com.mysql.jdbc.Connection;
      import com.mysql.jdbc.PreparedStatement;


      public class ImportData {

      /**
      * @param args
      */
      public static void main(String[] args) {
      try{
      Class.forName("com.mysql.jdbc.Driver");
      Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/project","root","admin");
      con.setAutoCommit(false);
      PreparedStatement pstm = null ;
      FileInputStream input = new FileInputStream("D://file.xlsx");

      XSSFWorkbook wb = new XSSFWorkbook(input);
      XSSFSheet sheet = wb.getSheetAt(0);
      Row row;
      for(int i=1; i<=sheet.getLastRowNum(); i++){
      row = sheet.getRow(i);
      int id = (int) row.getCell(0).getNumericCellValue();
      String name = row.getCell(1).getStringCellValue();
      String address = row.getCell(2).getStringCellValue();
      String sql = "INSERT INTO sree VALUES('"+id+"','"+name+"','"+address+"')";
      pstm = (PreparedStatement) con.prepareStatement(sql);
      pstm.execute();
      System.out.println("Import rows "+i);
      }
      con.commit();
      pstm.close();
      con.close();
      input.close();
      System.out.println("Success import excel to mysql table");
      }catch(ClassNotFoundException e){
      System.out.println(e);
      }catch(SQLException ex){
      System.out.println(ex);
      }catch(IOException ioe){
      System.out.println(ioe);
      }

      }

      }

      Delete
    2. HSSFRow row;
      for(int i=1; i<=sheet.getLastRowNum(); i++){
      row = sheet.getRow(i);
      int id = (int) row.getCell((short) 0).getNumericCellValue();

      String empid = row.getCell((short)1).getStringCellValue();

      String name = row.getCell((short)2).getStringCellValue();

      String bank = row.getCell((short)3).getStringCellValue();

      String bankAc = row.getCell((short)4).getStringCellValue();

      String desig = row.getCell((short)5).getStringCellValue();

      String panNo = row.getCell((short)6).getStringCellValue();

      String pfNo = row.getCell((short)7).getStringCellValue();

      Date date = row.getCell((short)8).getDateCellValue();
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
      String sDate= sdf.format(date);

      String compName = row.getCell((short)9).getStringCellValue();

      String gen = row.getCell((short)10).getStringCellValue();

      String sql = "INSERT INTO employee_details VALUES("+id+",'"+empid+"','"+name+"','"+bank+"','"+bankAc+"','"+desig+"','"+panNo+"','"+pfNo+"','"+sDate+"','"+compName+"','"+gen+"')";
      pstm = (PreparedStatement) con.prepareStatement(sql);
      pstm.execute();
      System.out.println("Import rows "+i);
      }

      Delete
  3. how to insert excel data to foreign key set table please help me?

    ReplyDelete
    Replies
    1. you need insert first in the table father

      Delete
  4. Anonymous2:40 AM

    Exception in thread "main" org.apache.poi.poifs.filesystem.OfficeXmlFileException: The supplied data appears to be in the Office 2007+ XML. You are calling the part of POI that deals with OLE2 Office Documents. You need to call a different part of POI to process this data (eg XSSF instead of HSSF)

    ReplyDelete
    Replies
    1. import java.io.FileInputStream;
      import java.io.IOException;
      import java.sql.DriverManager;
      import java.sql.SQLException;

      import org.apache.poi.openxml4j.opc.OPCPackage;
      import org.apache.poi.poifs.filesystem.POIFSFileSystem;
      import org.apache.poi.ss.usermodel.Row;
      import org.apache.poi.xssf.usermodel.XSSFSheet;
      import org.apache.poi.xssf.usermodel.XSSFWorkbook;

      import com.mysql.jdbc.Connection;
      import com.mysql.jdbc.PreparedStatement;


      public class ImportData {

      /**
      * @param args
      */
      public static void main(String[] args) {
      try{
      Class.forName("com.mysql.jdbc.Driver");
      Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/project","root","admin");
      con.setAutoCommit(false);
      PreparedStatement pstm = null ;
      FileInputStream input = new FileInputStream("D://file.xlsx");

      XSSFWorkbook wb = new XSSFWorkbook(input);
      XSSFSheet sheet = wb.getSheetAt(0);
      Row row;
      for(int i=1; i<=sheet.getLastRowNum(); i++){
      row = sheet.getRow(i);
      int id = (int) row.getCell(0).getNumericCellValue();
      String name = row.getCell(1).getStringCellValue();
      String address = row.getCell(2).getStringCellValue();
      String sql = "INSERT INTO sree VALUES('"+id+"','"+name+"','"+address+"')";
      pstm = (PreparedStatement) con.prepareStatement(sql);
      pstm.execute();
      System.out.println("Import rows "+i);
      }
      con.commit();
      pstm.close();
      con.close();
      input.close();
      System.out.println("Success import excel to mysql table");
      }catch(ClassNotFoundException e){
      System.out.println(e);
      }catch(SQLException ex){
      System.out.println(ex);
      }catch(IOException ioe){
      System.out.println(ioe);
      }

      }

      }

      Delete
  5. Thanks ! It worked perfectly fine....

    ReplyDelete
  6. I want to type Hindi/tamil Text in MySql and retrieve the datas in Hindi/Tamil i tried reulted in ????mark please help.

    ReplyDelete
  7. import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.Collections;
    import java.util.Scanner;
    public class reversedemo
    {

    public static void main(String args[])
    {
    Scanner sh = new Scanner(System.in);
    System.out.println("Enter a word");
    String str = sh.next();
    char[] ch = str.toCharArray();
    int y = str.length();

    for (int m = y ; m <= y; m--)
    {
    String pl1 = new String(ch,0,m);
    if(pl1.length()>=2)
    {
    //int l=8;
    char[] dh = new char[y];
    int c=y-1;
    int z = y-2;
    int g = y-1;
    char[] eh = new char[y];
    int h = 1;

    //int k =0;
    for (int j=c; j<=y; j--)
    {
    if(m>=2&&h<=8)
    {
    String mpm = new String(dh,0,y);
    dh[g] = ch[j];

    String pl = new String(ch,0,m);
    // String mpm = new String(dh,0,y);
    --m;


    System.out.println(""+pl+"/"+mpm.trim()+"");
    h++;
    g--;



    }
    }

    }
    }
    }
    }

    I WANT RESULT TILL
    applesandoranges/
    applesandorange/s
    applesandorang/es
    applesandoran/ges
    applesandora/nges
    applesandor/anges
    applesando/ranges
    applesand/oranges
    ------------------------------
    BUT I AM GETTING
    Enter a word
    applesandoranges
    applesandoranges/
    applesandorange/s
    applesandorang/es
    applesandoran/ges
    applesandora/nges
    applesandor/anges
    applesando/ranges
    applesand/oranges
    applesa/
    apples/s
    apple/es
    appl/ges
    app/nges
    ap/anges
    Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
    at java.lang.String.(String.java:208)
    at reversedemo.main(reversedemo.java:18)

    PLEASE SOLVE



    ReplyDelete
  8. I want to add values to 3 different tables..
    After Splitting each Words to its stemlist and suffixlist.

    ReplyDelete
  9. Ex: create table Word (Word varchar (20)); <------ Word table
    create table StemList(Stems varchar(20));<-------------stem table
    create table SuffixList (Suffixs varchar(20)); <-----------------Suffix table

    Splitting each word to its respective stemlist and suffixlist ditribute only last row to Word,stemlist,suffixlist table....

    ReplyDelete
  10. Hi,

    Your doing a excellent contribution to the developer community. Keep going!!

    I am new to apache poi. I hope your article gonna help me.
    I have a query whether if the same excel is imported to data repeatedly will there be any conflict of primary key(in case if any) for the above code.

    If yes then how can this be fixed.

    Pleased to hear from you.

    Thanks

    ReplyDelete
  11. XSSFWorkbook wb = new XSSFWorkbook(input); why error in this line

    ReplyDelete
  12. how to pass foreign key value in controller ?

    ReplyDelete
  13. Anonymous9:04 PM

    if some cell are empty i need to insert database column defalut value how can achive this pls hlp me

    ReplyDelete