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

标签 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>

上传.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

感谢您的帮助

最佳答案

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

希望对你有所帮助!!

关于java - 如何使用jsp浏览mysql数据库表中的文件存储excel的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36348467/

相关文章:

java - 选择包含特定 linkText 的元素之前的元素

mysql - 计算 IN 运算符中的匹配单词数

java - Tomcat6 MySql JDBC 数据源配置

vba - 替代命令 (ActiveSheet)

java - 如何在java中从特定行读取文件直到文件末尾

java - JPA 和 Hibernate 初始化非惰性集合错误

java - 为什么会抛出 ConcurrentModificationException 以及如何调试它

php - 功能有时只工作

vba - 使用 vba 将 ddmmmyyyy 转换为数字

VBA 将所有单元格格式化为文本