2013-04-17 116 views
0

我想使o程序从哪里读取excel文件中的数据,我将它们存储在数据库中。我使用eclipse作为编辑器和mySQL。我正在使用APACHE POI来读取连接的excel文件和JDBC。 excel文件的结构如下所示:在从excel文件读取后在mysql中存储数据

ID NAME SALARY STREET 
--- ---- ------ ------------- 
321 TIM 1254  14 avenue 
121 PAUL 1265  28h oktovriou 
432 NICK 4521  papaflessa 

我当然有很多这样的文件,其中包含更多的行和列。我的程序的目的是读取数据,创建名为excel文件名称的表,并将每个表的字段作为excel文件的第一行。之后,这些值将成为Excel文件的其余数据。 在下面的代码中,我设法读取它们,在控制台中显示数据。后期我试图用JDBC调用数据库,但是在创建表时我遇到了问题。

try 
      { 
       String[] allFields; 
       String createTableStr = "CREATE TABLE" + createTableStr 
        + "(" + org.apache.commons.lang3.StringUtils.join(allFields, 
        ",") + ")"; 

任何人都可以帮助我吗?

预先感谢您:)

import java.io.FileInputStream; 
import java.io.IOException; 
import java.util.ArrayList; 
import java.util.HashMap; 
import java.util.Iterator; 
import java.util.List; 

import org.apache.poi.hssf.usermodel.HSSFCell; 
import org.apache.poi.hssf.usermodel.HSSFRow; 
import org.apache.poi.hssf.usermodel.HSSFSheet; 
import org.apache.poi.hssf.usermodel.HSSFWorkbook; 
import org.apache.commons.lang3.StringUtils; 
import org.apache.poi.ss.usermodel.Cell; 

import java.sql.Connection; 
import java.sql.DriverManager; 
import java.sql.SQLException; 
import java.sql.Statement; 

public class exam1 { 

    @SuppressWarnings({ "unchecked", "unchecked" }) 
    static void main (String[] args) throws Exception { 

     String filename = "C:\\Users\\Efi\\Documents\\test5.xls"; 

     List sheetData = new ArrayList(); 
     FileInputStream fis = null; 
     try { 
      fis = new FileInputStream(filename); 
      HSSFWorkbook workbook = new HSSFWorkbook(fis); 
      HSSFSheet sheet = workbook.getSheetAt(0); 

      Iterator rows = sheet.rowIterator(); 
      while (rows.hasNext()) { 
       HSSFRow row = (HSSFRow) rows.next(); 
       Iterator cells = row.cellIterator(); 

       List data = new ArrayList(); 
        while (cells.hasNext()) { 
        HSSFCell cell = (HSSFCell) cells.next(); 
        data.add(cell); 
        } 
        sheetData.add(data); 
      } 

        } catch (IOException e) { 
        e.printStackTrace(); 
        } finally { 
        if (fis != null) { 
        fis.close(); 
        } 
        } 

    showExcelData(sheetData); 


    @SuppressWarnings("unused") 
    HashMap<String, String> tableFields = new HashMap(); 
      for (int i=0; i<sheetData.size();i++){ 
      List list = (List) sheetData.get(i); 
       for (int j=0; j<list.size(); j++){ 
       Cell cell = (Cell) list.get(j); 
       if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) { 
       System.out.print(cell.getNumericCellValue()); 

        }else if(cell.getCellType()==Cell.CELL_TYPE_STRING) { 


        System.out.print(cell.getRichStringCellValue()); 
       } else if(cell.getCellType()==Cell.CELL_TYPE_BOOLEAN) { 
      System.out.print(cell.getBooleanCellValue()); 
        } 
       if (j < list.size() - 1) { 
      System.out.print(", "); 
        }}} 
        } 

    private static void showExcelData(List sheetData) { 

     } 

    @SuppressWarnings("unchecked") 
    private HashMap parseExcelData (List sheetData){ 

      HashMap<String,Integer> tableFields = new HashMap(); 
      List list = (List) sheetData.get(0); 
      for (int j=0; j<list.size(); j++){ 
       Cell cell=(Cell) list.get(j); 
       tableFields.put(cell.getStringCellValue(),cell.getCellType()); 
     } 

      return tableFields; 

     } 



    @SuppressWarnings({ "unchecked", "unchecked", "unchecked", "unchecked", "unused" }) 
    private String getCreateTable(String tablename, HashMap<String, Integer> tableFields){ 
     Iterator iter = tableFields.keySet().iterator(); 
     String str=""; 
     String[] allFields = new String[tableFields.size()]; 
     int i = 0; 
     while (iter.hasNext()){ 
     String fieldName = (String) iter.next(); 
     Integer fieldType=(Integer)tableFields.get(fieldName); 

     switch (fieldType){ 
     case Cell.CELL_TYPE_NUMERIC: 
     str=fieldName + "INTEGER"; 
     break; 
     case Cell.CELL_TYPE_STRING: 
     str= fieldName + "VARCHAR(255)"; 
     break; 
     case Cell.CELL_TYPE_BOOLEAN: 
     str=fieldName + "INTEGER"; 
     break; 
      } 
     allFields[i++]= str; 
     } 
     return str; 
    } 

    public Connection getConnection() throws SQLException { 
     try { 
      Class.forName("com.mysql.jdbc.Driver"); 
      Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/kainourgia","root", "root"); 
      Statement stmt = con.createStatement(); 
      try 
      { 
      System.out.println("Use the database..."); 
      stmt.executeUpdate("USE kainourgia;"); 
      } 
      catch(SQLException e) 
      { 
      System.out.println("SQLException: " + e.getMessage()); 
      System.out.println("SQLState:  " + e.getSQLState()); 
      System.out.println("VendorError: " + e.getErrorCode()); 
      } 
      try 
      { 
       String[] allFields; 
       String createTableStr = "CREATE TABLE" + createTableStr 
        + "(" + org.apache.commons.lang3.StringUtils.join(allFields, 
        ",") + ")"; 

       System.out.println("Create a new table in the database"); 
       stmt.executeUpdate(createTableStr); 
       } 
      catch(SQLException e) 
      { 
      System.out.println("SQLException: " + e.getMessage()); 
      System.out.println("SQLState:  " + e.getSQLState()); 
      System.out.println("VendorError: " + e.getErrorCode()); 
      } 
      } 
      catch(Exception e) 
      { 
      System.out.println(((SQLException) e).getSQLState()); 
      System.out.println(e.getMessage()); 
      e.printStackTrace(); 
      } 
     return null; 
      } 

     } 
+0

“我在创建表格时出现问题。” - 问题是?告诉我们你得到了哪个例外...... –

+0

什么都没有,没有例外。只有在编辑器中,它表明我有错误。 – dedmar

+0

我意识到这是您的第一个问题,所以我认为您应该阅读[常见问题](http://stackoverflow.com/faq),了解如何制定您的问题。理想情况下,我们不应该花时间*找到问题,即你说出了什么问题,并试图找出解决方法;)。我敢打赌你的编译器/编辑会告诉你那里有什么问题。无论如何,当它还没有内容时,你正在创建和分配字符串createTableStr本身。此外,您正在连接新创建的字符串数组allFields,这将是空的 - 但我相信你知道这一点。 –

回答

0

您必须及彼编译错误:

  String[] allFields; 
      String createTableStr = "CREATE TABLE" + createTableStr 
       + "(" + org.apache.commons.lang3.StringUtils.join(allFields, 
       ",") + ")"; 

您收到此错误,因为你已经使用allFields没有初始化它。如果不首先进行初始化,则不能使用本地参考变量。初始化它然后使用它。此外,您应该使用从Excel文件中读取的列名的值对它进行初始化,以便正确创建表。

而且,我看你是铸造E要SQLException这里:

 catch(Exception e) 
     { 
     System.out.println(((SQLException) e).getSQLState()); 
     System.out.println(e.getMessage()); 
     e.printStackTrace(); 
     } 

因为如果E是的SQLException一个实例,它会被第一个catch抓住你不应该这样做,块。它已经达到第二个catch块表明它不是SQLException的实例。因此,当您尝试将其投射到SQLException时,它会生成ClassCastException

+0

任何想法我将如何做到这一点? – dedmar

+0

您必须从excel文件中读取列名,然后将它们分配给String数组。使用'allFields = new String [numberOfColumns];'初始化它,考虑到表中最多有20列。然后使用'allFields [1] =“ID”;'等来初始化单个对象。 –

+0

我想以编程方式做到这一点。我的意思是我将初始化它,但然后每个字段的初始化发生在我已经存储数据的数组列表中。我将如何做到这一点? – dedmar

相关问题