2015-05-09 6 views
0

У меня есть лист excel. Используя его информацию, я должен получить некоторые данные и сохранить их в таблице mysql.экспорт данных из excel в mysql

мой код:

<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> 
<%@page import="java.io.IOException"%> 
<%@page import="java.sql.SQLException"%> 
<%@page import="cnn.sem_year_conversion"%> 
<%@page import="org.apache.poi.ss.usermodel.Row"%> 
<%@page import="org.apache.poi.hssf.usermodel.HSSFCell"%> 
<%@page import="org.apache.poi.hssf.usermodel.HSSFRow"%> 
<%@page import="org.apache.poi.hssf.usermodel.HSSFSheet"%> 
<%@page import="org.apache.poi.hssf.usermodel.HSSFWorkbook"%> 
<%@page import="org.apache.poi.poifs.filesystem.POIFSFileSystem"%> 
<%@page import="java.util.Iterator"%> 
<%@page import="java.io.FileInputStream"%> 
<%@page import="java.util.ArrayList"%> 
<%@page import="java.sql.PreparedStatement"%> 
<%@page import="java.sql.Connection"%> 
<%@page import="cnn.cn"%> 
<%@page contentType="text/html" pageEncoding="UTF-8"%> 
<!DOCTYPE html> 
<html> 
    <head> 
     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
     <title>JSP Page</title> 
    </head> 
    <body> 

<% 
    try 
    { 
Connection con=cn.getcon(); 
PreparedStatement ps=null; 

    String name,f_name,branch="",enroll,status="regular",sem,elligible=""; 
int year= 0; 
int flag; 
int count=0; 
     con.setAutoCommit(false); 
     PreparedStatement pstm = null ; 
     FileInputStream input = new FileInputStream("C:/Users/intel/Documents/student_excel.xls"); 
     POIFSFileSystem fs = new POIFSFileSystem(input); //creating a new poi reference to the given excel file 
     HSSFWorkbook wb = new HSSFWorkbook(fs); 
     HSSFSheet sheet = wb.getSheetAt(0); 
     Row row; 
       for(int i=1; i<=sheet.getLastRowNum(); i++) 
       { 
        //points to the starting of excel i.e excel first row 
      row = (Row) sheet.getRow(i); //sheet number 
           if(row.getCell(1)==null) { enroll = "0";} //suppose excel cell is empty then its set to 0 the variable 
        else enroll = row.getCell(1).toString(); //else copies cell data to name variable 

            if(row.getCell(2)==null) { name = "0";} //suppose excel cell is empty then its set to 0 the variable 
        else name = row.getCell(2).toString(); //else copies cell data to name variable 

             if(row.getCell(3)==null) { f_name = "0";} //suppose excel cell is empty then its set to 0 the variable 
        else f_name = row.getCell(3).toString(); //else copies cell data to name variable 

    if(row.getCell(5)==null) { sem = "0";} //suppose excel cell is empty then its set to 0 the variable 
        else sem = row.getCell(5).toString(); //else copies cell data to name variable 

       switch (sem) { 
      case "1": 
      case "2": 
       year=1; 
       break; 
      case "3": 
      case "4": 
       year=2; 
       break; 
      case "5": 
      case "6": 
       year=3; 
       break; 
      case "7": 
      case "8": 
       year=4; 
       break; 
       default:year=0; 
     } 

     if(row.getCell(6)==null) { elligible="0";} //suppose excel cell is empty then its set to 0 the variable 
        else elligible = row.getCell(6).toString(); //else copies cell data to elligible variable 
if(elligible=="Submitted to RGPV"|| elligible=="Forwarded by RGPV") 
    flag=0; 
else 
    flag=1; 
    if(enroll.contains("AU")) 
     branch="au"; 
    else if(enroll.contains("EC")) 
     branch="ec"; 
    else if(enroll.contains("CS")) 
     branch="cs"; 
    else if(enroll.contains("CE")) 
     branch="ce"; 
    else if(enroll.contains("IT")) 
     branch="it"; 


String query="insert into student values(?,?,0,3,?,?,?)"; 
ps=con.prepareStatement(query); 
ps.setString(1, enroll); 
ps.setString(2, name); 
ps.setString(3, branch); 
ps.setInt(4,year); 
ps.setString(5, f_name); 
ps.setString(6, status); 


count=ps.executeUpdate(); 

       } 


//For checking data is inserted or not? 

      con.commit(); 
     pstm.close(); 
     con.close(); 
     input.close(); 
     if(count>0) 
     System.out.println("Successful import of excel to mysql table"); 

     else 
      System.out.println("Import Failed."); 

    } 

    catch(SQLException ex){ 
     out.println(ex); 
    }catch(IOException ioe)`{ 
     out.println(ioe); 
    } 


%> 

    </body> 
</html> 

Но это порождает следующую ошибку ---

HTTP Status 500 - Internal Server Error 

type Exception report 

messageInternal Server Error 

descriptionThe server encountered an internal error that prevented it from fulfilling this request. 

exception 

org.apache.jasper.JasperException: PWC6033: Error in Javac compilation for JSP 

PWC6199: Generated servlet error: 
source value 1.5 is obsolete and will be removed in a future release 

PWC6199: Generated servlet error: 
target value 1.5 is obsolete and will be removed in a future release 

PWC6199: Generated servlet error: 
To suppress warnings about obsolete options, use -Xlint:-options. 

PWC6197: An error occurred at line: 32 in the jsp file: /student_info.jsp 
PWC6199: Generated servlet error: 
strings in switch are not supported in -source 1.5 
    (use -source 7 or higher to enable strings in switch) 

note The full stack traces of the exception and its root causes are available in the GlassFish Server Open Source Edition 4.0 logs. 
GlassFish Server Open Source Edition 4.0 

Я использовал строки в переключатель случае, поскольку на использовании INT он дает exception-

org.apache.jasper.JasperException: java.lang.NumberFormatException: For input string: "1.0" 

Как это решить?

+0

Что вы попытались исправить эту ошибку? –

+0

Я не понял ошибку, так что я не смог ее решить – Archi

+0

Является ли эта ошибка из вашего текущего кода? Какая линия? Полная ошибка стека ошибок? Какова была ошибка с версией «int»? Какой jdk вы используете? –

ответ

0

Я думаю, что это должно быть исключением оператора switch, потому что коммутатор работает с байтовыми, короткими, char и int примитивными типами данных.

Попробуйте сначала преобразовать данные в целое число, прежде чем переключать его.

+0

Я попробовал это уже, но затем он дал исключение, упомянутое выше «NumberFormatexception» – Archi

+0

Ошибка NumberFormatexception, когда требуется преобразование строки в float. Поэтому я сначала преобразовал строковую переменную в float, а затем в int. И использовал версию int в корпусе коммутатора. Теперь код работает правильно. – Archi

Смежные вопросы