如何从4个Excel工作表中的Java数据中创建单个数据库表?

时间:2019-02-08 03:41:06

标签: java database

在我的项目中,我已经上传了excel工作表,并在接收到excel文件后使用Java进行检索,我只想创建一个数据库表。 这些excel表包含分数列表(每个excel表包含单个主题分数列表),例如学生姓名,内部,外部,结果。 如果这是一个Excel工作表,那么我可以轻松地在db中创建一个表。但是我必须从4张纸上创建一张桌子。

我只是尝试使用for循环列出每个excel文件,并逐个获取数据,但这不是我的解决方案。

STUDENT NAME    CIA  ESE      TOTAL

 AJAY G         46   31         77
 AJITH V        41   27         68
AJITH KUMAR     40   26         66

我的Java代码在这里:

 String dirs[] = file.list();
        for(String i:dirs) {
            // here i can get the file one by one 
            fis = new FileInputStream(fullpath+"/"+i);
            wb = WorkbookFactory.create(fis);
            System.out.println(wb.getNumberOfSheets());
            sh = wb.getSheet("Sheet1");
            int noOfRows = sh.getLastRowNum();
            int noOfCols = sh.getRow(7).getLastCellNum();
            System.out.println("Rows : "+ noOfRows);
            System.out.println("Cols : "+ noOfCols);
        }

以上是我的excel工作表数据,所有的工作表都一样,但主题不同(主题名称是文件名,因此我可以接受)。

我希望在db中创建一个表,如:

Table name : StudentResult

Stuname | Subject1 | Sub1CIA | Sub1ESE | Subject2 | Sub2CIA | Sub2ESE ...

依此类推(获取剩余的excel表格列)。

1 个答案:

答案 0 :(得分:1)

假设每个工作表都包含列标题,请从所有工作表中收集列标题,并进行一组唯一的设置。然后,您可以使用此集来创建数据库表,以使用JDBC动态执行DDL。

如果要在for循环之后创建表,请在for循环上方声明一个Set变量,并继续将每个工作表的列标题添加到其中。一旦控件退出for循环,您将获得带有列标题的集合。这是此伪代码

    // Declare a set here
    Set<String> dbColumns = new HashSet<String>();

    String dirs[] = file.list();
    for(String i:dirs) {

        // For each sheet
        // Get the heading row ( may be col 1 depending on the work sheet)

        // Get the cells from this row

        // Add the values to the dbColumns set
    }

    // Now dbColumns contains the list for columns to be created

    // Iterate through this set and form the DDL Statement

    // Execute the DDL using jdbc