如何使用jsp浏览mysql数据库表中的文件来存储excel的数据

时间:2016-04-01 05:09:06

标签: java mysql excel jsp apache-poi

我是Apache Poi和文件处理java的新手。所以我想要一些帮助

我在代码中通过excel文件路径完成了,但现在我想在代码中不提供文件路径。

所以现在我的问题是 如何使用jsp ???

在mysql数据库表中浏览文件来存储excel的数据

我想通过浏览计算机来选择excel文件。

的index.jsp

<body>
  <form action="upload.jsp" method="post" enctype="multipart/form-data">
        <table>
            <tr>
                <td ><B>UPLOAD THE FILE</B></td>
            </tr>
            <tr>
                <td><b>Choose the file To Upload:</b></td>
                <td><INPUT NAME="file" TYPE="file"></td>
            </tr>
            <tr>
                <td><input type="submit" value="Upload File"> </td>
            </tr>
        </table>
  </form>
</body>

upload.jsp

<body>

<%@ page import="java.io.*" %>
<%@ page import="java.sql.*" %>
<%@ page import="java.util.*"%>


<%@ page import="org.apache.poi.ss.usermodel.*"%>
<%@ page import="org.apache.poi.xssf.usermodel.XSSFSheet"%>
<%@ page import="org.apache.poi.xssf.usermodel.XSSFWorkbook"%>

<%
    String saveFile="";
    String contentType = request.getContentType();

    if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0))
    {
        DataInputStream in = new DataInputStream(request.getInputStream());
        int formDataLength = request.getContentLength();
        byte dataBytes[] = new byte[formDataLength];
        int byteRead = 0;
        int totalBytesRead = 0;

        while (totalBytesRead < formDataLength)
        {
            byteRead = in.read(dataBytes, totalBytesRead,formDataLength);
            totalBytesRead += byteRead;
        }

        String file = new String(dataBytes);

        saveFile = file.substring(file.indexOf("filename=\"") + 10);
        saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
        saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1,saveFile.indexOf("\""));

        int lastIndex = contentType.lastIndexOf("=");

        String boundary = contentType.substring(lastIndex + 1,contentType.length());

        int pos;

        pos = file.indexOf("filename=\"");
        pos = file.indexOf("\n", pos) + 1;
        pos = file.indexOf("\n", pos) + 1;
        pos = file.indexOf("\n", pos) + 1;

        int boundaryLocation = file.indexOf(boundary, pos) - 4;

        int startPos = ((file.substring(0, pos)).getBytes()).length;

        int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;

        File ff = new File(saveFile);

        FileOutputStream fileOut = new FileOutputStream(ff);
        fileOut.write(dataBytes, startPos, (endPos - startPos));

        fileOut.flush();
        fileOut.close();
%>

<table>
    <tr>
        <td><b>You have successfully upload the file:</b>
            <% out.println(saveFile);
            %>
        </td>
    </tr>
</table>

    <%
        Connection connection = null;
        ResultSet resultSet = null;
        PreparedStatement preparedStatement = null;
        FileInputStream fileInputStream;
            Statement stmt = null;
            File f = null;
            int count = 0;

        ArrayList<String> mylist = new ArrayList<String>();

        try
        {
            Class.forName("com.mysql.jdbc.Driver");  

            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/parag","root","tiger"); 
            System.out.println("connection sucessfulyyy");


            f = new File(saveFile);

            preparedStatement = connection.prepareStatement("insert into exlogin(username) values(?)");

            fileInputStream = new FileInputStream(f);

            preparedStatement.setBinaryStream(1, (InputStream)fileInputStream, (int)(f.length()));

            preparedStatement.executeUpdate();

            System.out.println("connection sucessfulyyy");

            resultSet = stmt.executeQuery("SELECT COUNT(*) FROM exlogin");

             while(resultSet.next())
                 {

                         int val = resultSet.getInt(1);

                         System.out.println(val);

                        count = val+1;

                }

                preparedStatement.setInt(1,count);

                /* We should now load excel objects and loop through the worksheet data */
                    fileInputStream  = new FileInputStream(f);
                    System.out.println("FileInputStream Object created..! "+filePath);

                /* Load workbook */
                XSSFWorkbook workbook = new XSSFWorkbook (fileInputStream);
                System.out.println("XSSFWorkbook Object created..! ");

                /* Load worksheet */
                XSSFSheet sheet = workbook.getSheetAt(0);
                System.out.println("XSSFSheet Object created..! ");

                // we loop through and insert data
            Iterator<Row> ite = sheet.rowIterator();
                System.out.println("Row Iterator invoked..! ");

                while(ite.hasNext()) 
               {
                    Row row = (Row) ite.next(); 

                    Iterator<Cell> cellIterator = row.cellIterator();
                    int index = 1;

                    while(cellIterator.hasNext()) 
                    {
                        Cell cell = cellIterator.next();

                        switch(cell.getCellType()) 
                        { 
                             case Cell.CELL_TYPE_STRING: //handle string columns
                                    preparedStatement.setString(index, cell.getStringCellValue()); 
                                    System.out.println("getting cell value..! "+cell.getStringCellValue());

                                      break;
                              case Cell.CELL_TYPE_NUMERIC: //handle double data

                                    double i = (double)cell.getNumericCellValue();

                                    preparedStatement.setFloat(index, (float) cell.getNumericCellValue());

                                    break;

                            }
                               index++;

                    }
                //we can execute the statement before reading the next row
                preparedStatement.executeUpdate();
                }

                /* Close input stream */
                   fileInputStream.close();
                   /* Close prepared statement */
                   preparedStatement.close();

                   /* Close connection */
                   connection.close();




        }

        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
    %>

</body>

数据库表

CREATE TABLE exlogin
(
  username varchar(100)
);

Excel文件数据

username
parag
ram
shree
tejas
jyoti

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

InputStream 对文件的访问运行时间

 if(ServletFileUpload.isMultipartContent(request)){
            try {
                List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
                for(FileItem item : multiparts){
                    if(!item.isFormField()){
                        InputStream inputStream= item.getInputStream();
                        Workbook workbook = new XSSFWorkbook(inputStream);
                    }   
                }
            }catch(Exception e){
                e.printStackTrace();
            }   
        }

希望对你有所帮助!!