使用未定义的列数插入mysql

时间:2018-05-14 03:20:49

标签: java mysql excel

我对java的插入查询有疑问。 我已经从excel文件中读取数据了,我想用这些数据导入MySQL,如果excel文件有3列,我可以使用

String sql="INSERT INTO tablename(column1,column2,colum3) value(...)

但是如果excel文件没有定义列数(例如excel_1.xlsx有3列,excel_2.xlsx有4列)。 我如何使用插入查询?任何人都可以给我任何建议吗?

1 个答案:

答案 0 :(得分:0)

您可以这样做:

FileInputStream excelFile = new FileInputStream(new File("yourExcelsheet.xsls"));
Workbook workbook = new XSSFWorkbook(excelFile);
Sheet datatypeSheet = workbook.getSheetAt(0);
Iterator<Row> iterator = datatypeSheet.iterator();

//int columnCount = 4;  
String columnArray[] = new String[]{"column1","column2","column3","column4","column5","column6"};       

//iterate row-wise
while (iterator.hasNext()) {
    String sql="INSERT INTO tablename";
    String columnNames = "";
    String valueString = "";
    String value = "";      
    int i=0;
    Row currentRow = iterator.next();
    Iterator<Cell> cellIterator = currentRow.iterator();

    //iterate column-wise
     while (cellIterator.hasNext()) {
        Cell currentCell = cellIterator.next();     
        value = currentCell.getStringCellValue();

        if(i != 0)
        {
            columnNames += ",";
            valueString += ",";
        }
        columnNames += columnArray[i] ;
        valueString += value;
        i++;
    }

   sql += "(" + columnNames + ") values (" + valueString + ");";

   System.out.println(sql);

}

<强>输出:

  

INSERT INTO tablename(column1,column2,column3,column4)值   (5,5,5,5);