2013-04-24 64 views
0

我必须做一个程序,我将从excel文件中读取数据并将这些数据加载到数据库中的表中。该表将具有Excel文件的名称,并且该表的字段将是位于Excel文件第一行中的数据。我已经编写了代码来读取excel文件并使用我想要的名称创建表格。另外我设法将数据存储在表格中。但是对于这两个操作,为了创建字段和将数据存储在表中,我使用了Hashmap。但是我在我的表格中得到的结果与我的excel文件中的结果不一样。为什么putHashmap不会显示连续的数据?

例如,在我的Excel文件中的数据是:

ID NAME SALARY

5恭2349000

6波莱纳1000

7劳拉12587458

8 EFI 34567

43 jim 45878

但是,当我跑我的程序是什么,我得到在我的基础是这样的:

名称ID薪金

2349000 5恭

琳娜6 1000

等数据混淆。

我的程序如下。任何人都可以帮助我为什么会发生在我的结果中? 预先感谢您。

import java.io.FileInputStream; 
import java.io.IOException; 
import java.util.ArrayList; 
import java.util.HashMap; 
import java.util.Map; 
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 readexcel { 
    static HashMap<String, Integer> tFields = new HashMap(); 
    static HashMap[] tData; 

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

     Class.forName("com.mysql.jdbc.Driver"); 
     Connection con = (Connection) DriverManager.getConnection(
       "jdbc:mysql://localhost:3306/kainourgia", "root", "root"); 
     Statement stmt = con.createStatement(); 
     // String filename = "C:\\Users\\Efi\\Documents\\test6.xls"; 
     String fullPath = "C:\\Users\\Efi\\Documents\\test9.xls"; 
     String Path = "C:\\Users\\Efi\\Documents\\"; 
     String filename = "test9.xml"; 
     String[] parts = filename.split("\\."); 
     String tablename = parts[0]; 

     //Create an ArrayList to store the data read from excel sheet. 
     List sheetData = new ArrayList(); 
     FileInputStream fis = null; 
     try { 
      //Create a FileInputStream that will be use to read the 
      // excel file. 
      fis = new FileInputStream(fullPath); 
      //Create an excel workbook from the file system 
      HSSFWorkbook workbook = new HSSFWorkbook(fis); 
      //Get the first sheet on the workbook. 
      HSSFSheet sheet = workbook.getSheetAt(0); 

      //store the data read on an ArrayList so that we can printed the 
      // content of the excel to the console. 
      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); 
     tFields = parseExcelColumnTitles(sheetData); 
     String str = getCreateTable(con, tablename, tFields); 
     tData = parseExcelColumnData(sheetData); 
     fillTable(con, tablename, tData); 
    } 

    // Iterates the data and print it out to the console. 
    private static void showExcelData(List sheetData) { 
     // 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(", "); 
       } 
      } 
      System.out.println(""); 
     } 
    } 

    @SuppressWarnings({ "unchecked", "unused" }) 
    private static HashMap parseExcelColumnTitles(List sheetData) { 
     // εδώ διαβάζω μόνο την γραμμή 0 κάθε φύλλου για να πάρω τους τίτλους 
     // των πεδίων 

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

     return tableFields; 

    } 

    @SuppressWarnings({ "unchecked", "unused" }) 
    private static HashMap[] parseExcelColumnData(List sheetData) { 
     // εδω πρέπει να μπει μια επανάληψη, από την γραμμή 1 μέχρι την 
     // τελευταία γραμμή του κάθε φύλλου 
     HashMap[] tousRows = new HashMap[sheetData.size() - 1]; 
     for (int rowCounter = 1; rowCounter < sheetData.size(); rowCounter++) { 

      List list = (List) sheetData.get(rowCounter); 

      HashMap<String, Integer> tableFields = new HashMap(list.size()); 
      String str; 
      String[] tousFields = new String[list.size()]; 
      int i = 0; 

      for (int j = 0; j < list.size(); j++) { 
       Cell cell = (Cell) list.get(j); 
       if (cell != null) { 
        if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) { 
         tableFields.put(String.valueOf(cell 
           .getNumericCellValue()), cell.getCellType()); 
        } else if (cell.getCellType() == Cell.CELL_TYPE_STRING) { 
         tableFields.put(cell.getStringCellValue(), cell 
           .getCellType()); 
        } else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) { 
         tableFields.put(String.valueOf(cell 
           .getBooleanCellValue()), cell.getCellType()); 
        } 
       } 

      } 
      tousRows[rowCounter - 1] = tableFields; 
     } 

     return tousRows; 

    } 

    private static String getCreateTable(Connection con, String tablename, 
      HashMap<String, Integer> tableFields) { 
     Iterator iter = tableFields.keySet().iterator(); 
     Iterator cells = 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; 
     } 
     try { 
      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 all = org.apache.commons.lang3.StringUtils.join(
         allFields, ","); 
       String createTableStr = "CREATE TABLE IF NOT EXISTS " 
         + tablename + " (" + all + ")"; 

       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) { 
     } 
     return str; 
    } 

    private static void fillTable(Connection con, String fieldname, 
      HashMap[] tableData) { 
     for (int row = 0; row < tableData.length; row++) { 
      HashMap<String, Integer> rowData = tableData[row]; 
      Iterator iter = rowData.entrySet().iterator(); 
      String str; 
      String[] tousFields = new String[rowData.size()]; 
      int i = 0; 
      while (iter.hasNext()) { 
       Map.Entry pairs = (Map.Entry) iter.next(); 
       Integer fieldType = (Integer) pairs.getValue(); 
       String fieldValue = (String) pairs.getKey(); 
       switch (fieldType) { 
       case Cell.CELL_TYPE_NUMERIC: 
        str = fieldValue; 
        break; 
       case Cell.CELL_TYPE_STRING: 
        str = "\'" + fieldValue + "\'"; 
        break; 
       case Cell.CELL_TYPE_BOOLEAN: 
        str = fieldValue; 
        break; 
       default: 
        str = ""; 
        break; 
       } 
       tousFields[i++] = str; 
      } 

      try { 
       Statement stmt = con.createStatement(); 
       System.out.println("Use the table"); 
       String all = org.apache.commons.lang3.StringUtils.join(
         tousFields, ","); 
       String sql = "INSERT INTO " + fieldname + " VALUES (" + all 
         + ")"; 
       stmt.executeUpdate(sql); 
      } catch (SQLException e) { 
       System.out.println("SQLException: " + e.getMessage()); 
       System.out.println("SQLState: " + e.getSQLState()); 
       System.out.println("VendorError: " + e.getErrorCode()); 
      } 

     } 

     // return str; 
    } 

    private Statement createStatement() { 
     return null; 
    } 

} 

回答

1

发生这种情况是因为这是HashMap设计用于工作的方式。正如javadoc说:

“这一类并没有保证,而地图的顺序”

如果您有什么可以在插入顺序进行迭代的地图使用LinkedHashMap

+0

谢谢你的回复!:) – dedmar 2013-04-24 13:52:36

3

LinkedHashMap而不是HashMap恰恰就是您要找的。

来自Javadoc:HashMap“类不能保证地图的顺序;特别是,它不能保证顺序会随着时间的推移保持不变。”

如果您需要一致的订购,可以使用LinkedHashMap(用于插入/访问订单)或TreeMap(用于比较订单)。请注意,这些保持键的顺序,而不是数值。

+0

谢谢你的帮助!:) – dedmar 2013-04-24 11:59:32

+0

很高兴帮助。如果它对你有用,请不要忘记接受回应;) – TheEwook 2013-04-24 12:01:31

相关问题