2012-12-23 72 views
0

我正在讀取使用java POI的Excel表格中的值,並且需要插入到數據庫中。我從Excel表格中獲取字符串,數字和日期值以及第一個字段是列標題。如何插入數據庫使用java POI從Excel表中讀取數據?

public class SimpleExcelReadExample { 
    static Connection con1 = null; 
    static Connection con3 = null; 
    static PreparedStatement preparedstatement = null; 
    static ResultSet resultset = null; 
    int j = 0; 

    public static void main(String[] args) { 

     String fileName = "D:/Excel/Report.xls"; 
     Cleartables.table_daily_report(); 
     Vector dataHolder = read(fileName); 
     saveToDatabase(dataHolder); 
    } 

    public static Vector read(String fileName) { 
     Vector cellVectorHolder = new Vector(); 
     try { 
       FileInputStream myInput = new FileInputStream(fileName); 
       POIFSFileSystem myFileSystem = new POIFSFileSystem(myInput); 
       HSSFWorkbook myWorkBook = new HSSFWorkbook(myFileSystem); 
       HSSFSheet mySheet = myWorkBook.getSheetAt(0); 
       Iterator rowIter = mySheet.rowIterator(); 
       while (rowIter.hasNext()) { 
        HSSFRow myRow = (HSSFRow) rowIter.next(); 
        Iterator cellIter = myRow.cellIterator(); 
        Vector cellStoreVector = new Vector(); 
        while (cellIter.hasNext()) { 
          HSSFCell myCell = (HSSFCell) cellIter.next(); 
          //System.out.println("read method"+myCell); 
          cellStoreVector.addElement(myCell); 
        } 
        cellVectorHolder.addElement(cellStoreVector); 
       } 
     } catch (Exception e) { 
       e.printStackTrace(); 
     } 
     return cellVectorHolder; 
    } 

    private static void saveToDatabase(Vector dataHolder) 
    { 

        for (int i=0;i<dataHolder.size(); i++) 
        { 
         Vector cellStoreVector=(Vector)dataHolder.elementAt(i); 
         for (int j=0; j < cellStoreVector.size();j++) 
        { 
          System.out.println("show....."); 
          HSSFCell myCell = (HSSFCell)cellStoreVector.elementAt(j); 

          Please help me here....How to get the each column values ? 
        } 
+0

對(INT I = 0; I user441978

+0

但我收到列標題也...但數據庫table.So如何檢索沒有標題的值? – user441978

+0

標題只在第一行,對不對?那麼就跳過那一行? –

回答

1
try { 

     FileInputStream file = new FileInputStream(new File("E://Imp/Details.xlsx")); 
     XSSFWorkbook workbook = new XSSFWorkbook(file); 
     XSSFSheet sheet = workbook.getSheetAt(0); 
     Iterator<Row> rowIterator = sheet.iterator(); 
     rowIterator.next(); 
     while(rowIterator.hasNext()) 
     { 
      Row row = rowIterator.next(); 
      //For each row, iterate through each columns 
      Iterator<Cell> cellIterator = row.cellIterator(); 

      while(cellIterator.hasNext()) 
      { 
       Cell cell = cellIterator.next(); 
       //This will change all Cell Types to String 
       cell.setCellType(Cell.CELL_TYPE_STRING); 
       switch(cell.getCellType()) 
       { 
        case Cell.CELL_TYPE_BOOLEAN: 
         System.out.println("boolean===>>>"+cell.getBooleanCellValue() + "\t"); 
         break; 
        case Cell.CELL_TYPE_NUMERIC: 

         break; 
        case Cell.CELL_TYPE_STRING: 

         list.add(cell.getStringCellValue()); 

               break; 
       } 


      } 
      name=row.getCell(0).getStringCellValue(); 
      empid=row.getCell(1).getStringCellValue(); 
      add=row.getCell(2).getStringCellValue(); 
      mobile=row.getCell(3).getStringCellValue(); 
      System.out.println(name+empid+add+mobile); 
      ex.InsertRowInDB(name,empid,add,mobile); 
      System.out.println(""); 


     } 
     file.close(); 
    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    } 
    public void InsertRowInDB(String name,String empid,String add,String mobile) throws SQLException{ 

     Statement stmt=db.con.createStatement(); 
     PreparedStatement ps=null; 
     String sql="Insert into Employee(Name,EmployeeId,Address,ContactInfo) values(?,?,?,?)"; 
     ps=db.con.prepareStatement(sql); 
     ps.setString(1, name); 
     ps.setString(2, empid); 
     ps.setString(3, add); 
     ps.setString(4, mobile); 
    ps.executeUpdate(); 
    System.out.println("Values Inserted Successfully"); 
    } 
} 
+0

使用靜態字符串名稱,empid,add,mobile作爲類變量。 – JavaFreak

0

試試這個:

嘗試{

 String jdbc_insert_sql = "INSERT INTO TBL_PUNETORET" 
       + "(NUMRI_PERSONAL, EMRI_MBIEMRI,DATELINDJA,ADRESA,TELEFONI,DATA_PUNSIMIT,DATA_LARGIMIT,NJESIA,POZITA,TELEFONI_P,EMAIL,PERSHKRIMI,PUNTORI,REKOMANDUAR) " 
       + "VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; 
     Class.forName("oracle.jdbc.driver.OracleDriver"); 

     PreparedStatement preStatement = con.prepareStatement(jdbc_insert_sql); 
     con.setAutoCommit(false); 

     FileInputStream input = new FileInputStream(filename); 
     POIFSFileSystem fs = null; 
     try { 
      fs = new POIFSFileSystem(input); 
     } catch (IOException ex) { 
      Logger.getLogger(PunetoretForm.class.getName()).log(Level.SEVERE, null, ex); 
     } 
     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 numripersonal = (int) (row.getCell(0).getNumericCellValue()); 
      //String numripersonal = row.getCell(0).getStringCellValue(); 
      String emri = row.getCell(1).getStringCellValue(); 
      Date datelindja = row.getCell(4).getDateCellValue(); 
      DateFormat df = new SimpleDateFormat("dd/MMM/yyyy"); 
      String reportDate = df.format(datelindja); 
      df.parse(reportDate); 
      String adresa = row.getCell(5).getStringCellValue(); 
      int telefoni = (int) (row.getCell(6).getNumericCellValue()); 
      //String telefoni = row.getCell(4).getStringCellValue(); 
      Date datap = row.getCell(7).getDateCellValue(); 
      df = new SimpleDateFormat("dd/MMM/yyyy"); 
      String reportDatap = df.format(datap); 
      df.parse(reportDatap); 

      Date datal = row.getCell(8).getDateCellValue(); 
      String ss = null; 
      if (datal != null) { 
       df = new SimpleDateFormat("dd/MMM/yyyy"); 
       ss = df.format(datal); 
       df.parse(ss); 

      } 

      String njesia = row.getCell(9).getStringCellValue(); 
      String pozita = row.getCell(10).getStringCellValue(); 
      int telp = (int) (row.getCell(11).getNumericCellValue()); 
      if (telp == 0) { 
       String s = String.valueOf(telp); 
       s = "Ska numer"; 
      } 
      //String telp = row.getCell(9).getStringCellValue(); 
      String email = row.getCell(12).getStringCellValue(); 
      String pershkrimi = row.getCell(13).getStringCellValue(); 
      String punetori = row.getCell(14).getStringCellValue(); 
      String rekomanduar = row.getCell(15).getStringCellValue(); 
      if (datal == null) { 
       String sql = "INSERT INTO TBL_PUNETORET (NUMRI_PERSONAL, EMRI_MBIEMRI,DATELINDJA,ADRESA,TELEFONI,DATA_PUNSIMIT,DATA_LARGIMIT,NJESIA,POZITA,TELEFONI_P,EMAIL,PERSHKRIMI,PUNTORI,REKOMANDUAR) " 
         + "VALUES('" + numripersonal + "','" + emri + "','" + reportDate + "','" + adresa + "','" + telefoni + "','" + reportDatap + "'," + datal + ",'" + njesia + "','" + pozita + "','" + telp + "','" + email + "','" + pershkrimi + "','" + rekomanduar + "','" + punetori + "')"; 
       preStatement = (PreparedStatement) con.prepareStatement(sql); 
       preStatement.execute(); 
      } 
-1

如何從Excel工作表中讀取數據,並插入到數據庫表中的Java

如果( fileName.endsWith(「。xls」)){

   CustomerVo customerVo = new CustomerVo();//your vo 
       File myFile = new File("file location" + fileName); 
       FileInputStream fis = new FileInputStream(myFile); 

       // Finds the workbook instance for XLSX file 

       org.apache.poi.ss.usermodel.Workbook workbook = null; 
       try { 
        workbook = WorkbookFactory.create(fis); 
       } catch (InvalidFormatException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } 
       Row row = null; 
       // Return first sheet from the XLSX workbook 
       org.apache.poi.ss.usermodel.Sheet sheet = workbook.getSheetAt(0); 

       // Get iterator to all the rows in current sheet 
       Iterator<Row> rowIterator = sheet.iterator(); 
       int i = 0; 
       // Traversing over each row of XLSX file 
       while (rowIterator.hasNext()) { 

        row = rowIterator.next(); 
        Iterator<Cell> cellIterator = row.cellIterator(); 
        if (i != 0) { 

         while (cellIterator.hasNext()) { 
          Cell cell = cellIterator.next(); 
          if (i != 0) { 
           switch (cell.getCellType()) { 
           case Cell.CELL_TYPE_STRING: 
            System.out.print(cell.getStringCellValue()); 
            customerVo.setName(row.getCell(1).getStringCellValue()); 
            customerVo.setSex(row.getCell(2).getStringCellValue()); 

            DateFormat formatter = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy"); 
            Date date; 
            try { 
             date = (Date) formatter.parse(row.getCell(3).getStringCellValue()); 
             customerVo.setDob(date); 
            } catch (ParseException e) { 
             // TODO Auto-generated catch block 
             e.printStackTrace(); 
            } 

            customerVo.setEmail(row.getCell(4).getStringCellValue()); 
            customerVo.setAddress(row.getCell(6).getStringCellValue()); 
            customerVo.setCity(row.getCell(8).getStringCellValue()); 
            customerVo.setState(row.getCell(9).getStringCellValue()); 
            break; 
           case Cell.CELL_TYPE_BOOLEAN: 
            System.out.print(cell.getBooleanCellValue()); 
            break; 
           case Cell.CELL_TYPE_NUMERIC: 
            System.out.print(cell.getNumericCellValue()); 
            customerVo.setAccountnumber((int) row.getCell(0).getNumericCellValue()); 
            customerVo.setPincode((int) row.getCell(7).getNumericCellValue()); 
            customerVo.setBalance((int) row.getCell(10).getNumericCellValue()); 
            customerVo.setMobile((long) row.getCell(5).getNumericCellValue()); 
            break; 
           } 
           System.out.print(" - "); 
          } 
          i++; 

         } 
         System.out.println(customerVo);//your data store in the object 
         fileUploadService.customerFile(customerVo);//this method using mvc service to dao impl 
        } 
        i++; 
       } 
      } 

//用於存儲文件,數據庫

@Repository 公共類FileUploadDAOImpl實現FIleUploadDAO {

@Autowired 
private DataSource dataSource; 


@Override 
public CustomerVo customerFile(CustomerVo customerVo) { 

    String query = "insert into file_upload_table(name,sex,dob,email,mobile,address,pincode,city,state,balance,account_number)" 
      + "values(?,?,?,?,?,?,?,?,?,?,?)"; 

    Connection connection = null; 
    try { 
     connection = dataSource.getConnection(); 

     Date oldDate = new Date(customerVo.getDob().getTime()); 

     java.sql.PreparedStatement ps = null; 
     java.sql.ResultSet rs = null; 
     try { 
      ps = connection.prepareStatement(query); 
      // ps.setLong(1, customerVO.getAccountNo()); 
      ps.setString(1, customerVo.getName()); 
      ps.setString(2, customerVo.getSex()); 
      ps.setDate(3,oldDate); 
      ps.setString(4, customerVo.getEmail()); 
      ps.setLong(5, customerVo.getMobile()); 
      ps.setString(6, customerVo.getAddress()); 
      ps.setLong(7, customerVo.getPincode()); 
      ps.setString(8, customerVo.getCity()); 
      ps.setString(9, customerVo.getState()); 
      ps.setLong(10, customerVo.getBalance()); 
      ps.setLong(11, customerVo.getAccountnumber()); 
      ps.executeUpdate(); 

     } catch (SQLException e) { 
      // TODO: handle exception 
      e.printStackTrace(); 
     } 


    } catch (SQLException e) { 

     // TODO Auto-generated catch block 

     e.printStackTrace(); 
    } 
0

這是我寫的相同操作的代碼。請注意,我還創建了一個僱員Java類與所有這4個屬性:ID,名字,性別工資與他們的getter-setters。

package com.hibernate.poiex2; 

import java.io.FileInputStream; 
import java.io.FileNotFoundException; 
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 java.util.Iterator; 
import java.util.Properties; 
import org.apache.poi.ss.usermodel.Cell; 
import org.apache.poi.ss.usermodel.CellType; 
import org.apache.poi.ss.usermodel.Row; 
import org.apache.poi.xssf.usermodel.XSSFRow; 
import org.apache.poi.xssf.usermodel.XSSFSheet; 
import org.apache.poi.xssf.usermodel.XSSFWorkbook; 

/** 
* 
* @author nidhi 
*/ 
public class POIex2 { 

    XSSFRow row; 
    Employee e = new Employee(); 

    public static void main(String[] args) throws IOException { 

     String fileName = "/home/nidhi/Downloads/Employees.xlsx"; 
     POIex2 poIex2 = new POIex2(); 
     poIex2.readFile(fileName); 
    } 

    public void readFile(String fileName) throws FileNotFoundException, IOException { 
     FileInputStream fis; 
     try { 
      System.out.println("-------------------------------READING THE SPREADSHEET-------------------------------------"); 
      fis = new FileInputStream(fileName); 
      XSSFWorkbook workbookRead = new XSSFWorkbook(fis); 
      XSSFSheet spreadsheetRead = workbookRead.getSheetAt(0); 

      Iterator< Row> rowIterator = spreadsheetRead.iterator(); 
      while (rowIterator.hasNext()) { 
       row = (XSSFRow) rowIterator.next(); 
       Iterator< Cell> cellIterator = row.cellIterator(); 

       while (cellIterator.hasNext()) { 
        Cell cell = cellIterator.next(); 
        cell.setCellType(CellType.STRING); 
        switch (cell.getColumnIndex()) { 
         case 0: 
          System.out.print(
            cell.getStringCellValue() + " \t\t"); 
          break; 
         case 1: 
          System.out.print(
            cell.getStringCellValue() + " \t\t"); 
          break; 
         case 2: 
          System.out.print(
            cell.getStringCellValue() + " \t\t"); 
          break; 
         case 3: 
          System.out.print(
            cell.getStringCellValue() + " \t\t"); 
          break; 
         case 4: 
          System.out.print(
            cell.getStringCellValue() + " \t\t"); 
          break; 
        } 
       } 
       System.out.println(); 
       e.empId = Integer.parseInt(row.getCell(0).getStringCellValue()); 
       e.empName = row.getCell(1).getStringCellValue(); 
       e.gender = row.getCell(2).getStringCellValue(); 
       e.salary = row.getCell(3).getStringCellValue(); 

       InsertRowInDB(e.empId, e.empName, e.gender, e.salary); 
      } 
      System.out.println("Values Inserted Successfully"); 

      fis.close(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 

    public void InsertRowInDB(int empId, String empName, String gender, String salary) { 

     Float salaryDB = Float.parseFloat(salary); 
     try { 

      Properties properties = new Properties(); 
      properties.setProperty("user", "root"); 
      properties.setProperty("password", "root"); 
      properties.setProperty("useSSL", "false"); 
      properties.setProperty("autoReconnect", "true"); 

      Class.forName("com.mysql.jdbc.Driver"); 
      Connection connect = DriverManager.getConnection("jdbc:mysql://localhost:3306/Attendance", properties); 
      Statement stmt = connect.createStatement(); 
      PreparedStatement ps = null; 
      String sql = "INSERT INTO `Attendance`.`Employee_Master`\n" 
        + "(`EmployeeId`,\n" 
        + "`EmployeeName`,\n" 
        + "`Gender`,\n" 
        + "`Salary`)\n" 
        + "VALUES(?,?,?,?)"; 
      ps = connect.prepareStatement(sql); 
      ps.setInt(1, empId); 
      ps.setString(2, empName); 
      ps.setString(3, gender); 
      ps.setFloat(4, salaryDB); 
      ps.executeUpdate(); 
      connect.close(); 
     } catch (ClassNotFoundException | SQLException e) { 
      e.printStackTrace(); 
     } 
    } 
} 
0

嘗試這種

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

import org.apache.poi.ss.usermodel.Row; 
import org.apache.poi.xssf.usermodel.XSSFSheet; 
import org.apache.poi.xssf.usermodel.XSSFWorkbook; 
import org.hibernate.Session; 
import org.hibernate.SessionFactory; 
import org.hibernate.Transaction; 
import org.hibernate.cfg.AnnotationConfiguration; 

import com.mani.beans.Student; 

public class ReadDataFromExcel { 
    public static void main(String args[]) throws IOException { 
     SessionFactory sf = new AnnotationConfiguration().configure("com/mani/resources/hibernate.cfg.xml").buildSessionFactory(); 
     Session session = sf.openSession(); 
     FileInputStream file = new FileInputStream(new File("C:/Users/mani/Desktop/data.xlsx")); 
     XSSFWorkbook workbook = new XSSFWorkbook(file); 
     XSSFSheet sheet = workbook.getSheetAt(1); 
     Row row; 
     for(int i=1; i<=sheet.getLastRowNum(); i++){ //points to the starting of excel i.e excel first row 
      row = (Row) sheet.getRow(i); //sheet number 


       String id; 
       if(row.getCell(0)==null) { id = "0"; } 
       else id= row.getCell(0).toString(); 

        String name; 
       if(row.getCell(1)==null) { name = "null";} //suppose excel cell is empty then its set to 0 the variable 
        else name = row.getCell(1).toString(); //else copies cell data to name variable 

        String address; 
       if(row.getCell(2)==null) { address = "null"; } 
        else address = row.getCell(2).toString(); 
     Transaction t = session.beginTransaction(); 
     Student std = new Student(); 
     std.setId(Double.parseDouble(id)); 
     std.setName(name); 
     std.setAddress(address); 
     System.out.println(std.getId()+" "+std.getName()+" "+std.getAddress()); 
     session.saveOrUpdate(std); 
     t.commit();  
     } 
     file.close(); 
    } 


}` 
相關問題