0

我必须编写一个程序,从 Excel 文件中读取数据并将这些数据加载到数据库中的表中。该表将具有 excel 文件的名称,表的字段将是 excel 文件第一行中的数据。我已经编写了代码来读取 excel 文件并使用我想要的名称创建表。我还设法将数据存储在表中。但是对于这两个操作,创建字段和将数据存储在表中,我使用的是 Hashmap。但是我在表格中得到的结果与我的 excel 文件中的序列不同。

例如我的excel文件中的数据是:

身份证 姓名 工资

5 克里斯汀 2349000

6 宝莲娜 1000

7 劳拉 12587458

8 电喷 34567

43 吉姆 45878

但是当我运行我的程序时,我在我的基础中得到的是:

姓名 身份证 工资

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;
    }

}
4

2 回答 2

3

LinkedHashMap而不是HashMap正是您要寻找的。

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

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

于 2013-04-24T11:39:24.437 回答
1

之所以会发生这种情况,是因为这HashMap就是设计的工作方式。正如javadoc所说:

“此类不保证地图的顺序”

如果您有什么可以按插入顺序迭代的地图,请使用LinkedHashMap.

于 2013-04-24T11:39:22.807 回答