上传+;使用POI读取jsp中的excel文件

上传+;使用POI读取jsp中的excel文件,excel,file-upload,apache-poi,fileinputstream,apache-commons-fileupload,Excel,File Upload,Apache Poi,Fileinputstream,Apache Commons Fileupload,我想在JSP中读取一个excel文件,为此,我首先使用web应用程序项目将该文件上传到:D分区中名为uploads的文件夹中,我试着用另一个java项目读取excel上传的文件。这两个代码都在工作。下面是通过web应用程序项目(JSP和SERVLET)上传到特定文件夹中的代码: 库 <%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head>

我想在JSP中读取一个excel文件,为此,我首先使用web应用程序项目将该文件上传到:D分区中名为uploads的文件夹中,我试着用另一个java项目读取excel上传的文件这两个代码都在工作。下面是通过web应用程序项目(JSP和SERVLET)上传到特定文件夹中的代码:

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Upload File</title>
</head>
<body>
<form action="UploadFile" method="post" enctype="multipart/form-data">
Select File : <input type="file" name="filetoupload">
<br/>
<input type="submit" value="Upload File">
</form>
</body>
</html>
  • commons-fileupload-1.2.2.jar
  • commons-io-2.1.jar
  • index.jsp

    <%@page contentType="text/html" pageEncoding="UTF-8"%>
    <!DOCTYPE html>
    <html>
    <head>
    <title>Upload File</title>
    </head>
    <body>
    <form action="UploadFile" method="post" enctype="multipart/form-data">
    Select File : <input type="file" name="filetoupload">
    <br/>
    <input type="submit" value="Upload File">
    </form>
    </body>
    </html>
    
    然后,我创建了一个新的JAVA项目(SWING),并尝试了通过POI读取EXCEL文件的代码,该代码同样有效,下面是代码:

  • dom4j-1.6.1.jar
  • poi-3.10-FINAL-20140208.jar
  • poi-ooxml-3.9-20121203.jar
  • poi-ooxml-schemas-3.9-20121203.jar
  • xmlbeans-2.3.0.jar
  • JavaApplication.java

    import java.io.*;
    import java.util.Iterator;
    import org.apache.poi.ss.usermodel.Cell;
    import org.apache.poi.ss.usermodel.Row;
    import org.apache.poi.xssf.usermodel.XSSFSheet;
    import org.apache.poi.xssf.usermodel.XSSFWorkbook;
    
    public class JavaApplication{
    public static void main(String[] args){
    try{
    FileInputStream file;
    file = new FileInputStream(new File("D:\\upload\\total.xlsx"));
    
    //Create Workbook instance holding reference to .xlsx file
    XSSFWorkbook workbook = new XSSFWorkbook(file);
    
    //Get first/desired sheet from the workbook
    XSSFSheet sheet = workbook.getSheetAt(0);
    
    //Iterate through each rows one by one
    Iterator<Row> rowIterator = sheet.iterator();
    while (rowIterator.hasNext()){
    Row row = rowIterator.next();
    //For each row, iterate through all the columns
    Iterator<Cell> cellIterator = row.cellIterator();
    
    while (cellIterator.hasNext()){
    Cell cell = cellIterator.next();
    
    //Check the cell type and format accordingly
    switch (cell.getCellType()){
    case Cell.CELL_TYPE_NUMERIC:
    System.out.print(cell.getNumericCellValue() + "t");
    break;
    case Cell.CELL_TYPE_STRING:
    System.out.print(cell.getStringCellValue() + "t");
    break;
    }
    }
    System.out.println("");
    }
    file.close();
    } 
    catch (Exception e) 
    {
    e.printStackTrace();
    }
    }
    }
    
    import java.io.*;
    导入java.util.Iterator;
    导入org.apache.poi.ss.usermodel.Cell;
    导入org.apache.poi.ss.usermodel.Row;
    导入org.apache.poi.xssf.usermodel.xssfheet;
    导入org.apache.poi.xssf.usermodel.xssf工作簿;
    公共类Java应用程序{
    公共静态void main(字符串[]args){
    试一试{
    文件输入流文件;
    file=newfileinputstream(新文件(“D:\\upload\\total.xlsx”);
    //创建包含对.xlsx文件引用的工作簿实例
    XSSF工作簿=新XSSF工作簿(文件);
    //从工作簿中获取第一张/所需的工作表
    XSSFSheet sheet=workbook.getSheetAt(0);
    //逐个遍历每一行
    迭代器rowIterator=sheet.Iterator();
    while(roweiterator.hasNext()){
    行=行迭代器。下一步();
    //对于每一行,遍历所有列
    迭代器cellIterator=row.cellIterator();
    while(cellIterator.hasNext()){
    Cell=cellIterator.next();
    //检查相应的单元格类型和格式
    开关(cell.getCellType()){
    case Cell.Cell\u类型\u数值:
    System.out.print(cell.getNumericCellValue()+“t”);
    打破
    case Cell.Cell\u类型\u字符串:
    System.out.print(cell.getStringCellValue()+“t”);
    打破
    }
    }
    System.out.println(“”);
    }
    file.close();
    } 
    捕获(例外e)
    {
    e、 printStackTrace();
    }
    }
    }
    
    问题是,如何将这两个代码混合起来,才能上载文件,然后将EXCEL中的数据打印到JSP中的表格中????帮帮我,在
    项之后,我在这个过程中被困了一个多月添加此

    InputStream inputStream= new ByteArrayInputStream(IOUtils.toByteArray(new FileInputStream(f)));
    
    Workbook wb = WorkbookFactory.create(inputStream);
    Sheet mySheet = wb.getSheetAt(0);
    Iterator<Row> rowIter = mySheet.rowIterator();
    rowIter.next();
    
    InputStream InputStream=newbytearrayinputstream(IOUtils.toByteArray(newfileinputstream(f));
    工作簿wb=WorkbookFactory.create(inputStream);
    工作表mySheet=wb.getSheetAt(0);
    迭代器rowIter=mySheet.rowitter();
    rowIter.next();
    
    从这里继续您的代码。

    
    
    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
        pageEncoding="ISO-8859-1"%>
        <%@ page import="org.apache.poi.hssf.usermodel.HSSFCell"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Insert title here</title>
    </head>
    <body>
    <%
    //HSSFCell cell=new HSSFCell();
    //cell.
    %>
    <form action="uploadExcelsb123.jsp" method="post" enctype="multipart/form-data">
    Name: <input type="file" name="excel"><br>
    <input type="submit"" name="Upload">
    </form>
    </body>
    </html>
    
    
    
    
    
    <%@page import="java.sql.Connection"%>
    <%@page import="java.sql.PreparedStatement"%>
    
    <%@page import="org.apache.commons.io.IOUtils"%>
    <%@ page
        import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
    <%@ page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
    <%@ page import="org.apache.commons.fileupload.*"%>
    <%@ page import="com.api.dao.MyDataConnect"%>
    
    <%@ page import="java.util.*,java.io.*"%>
    <%@ page import="java.util.Iterator"%>
    <%@ page import="java.util.List"%>
    <%@ page import="java.util.Map"%>
    <%@ page import="java.io.File"%>
    <%@ 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="com.api.dao.MyDataConnect;"%><html>
    <head>
    <title>Bulk Upload Page</title>
    </head>
    <body>
    
    <%
    Map<String,String> mp=new HashMap<String,String>();
        try {
            String ImageFile = "";
            String itemName = "";
            boolean isMultipart = ServletFileUpload
                    .isMultipartContent(request);
            if (!isMultipart) {
            } else {
                FileItemFactory factory = new DiskFileItemFactory();
                ServletFileUpload upload = new ServletFileUpload(factory);
                List items = null;
                try {
                    items = upload.parseRequest(request);
                } catch (FileUploadException e) {
                    e.getMessage();
                }
    
                Connection conn = new MyDataConnect().giveConnection();
                //Date d = new Date();
                FileItem item = (FileItem) items.get(0);
    
                //InputStream is=item.getInputStream();
                 HSSFWorkbook workbook = new HSSFWorkbook(item.getInputStream());
                 String ipaddress=request.getRemoteAddr();
                 HSSFSheet sh = (HSSFSheet) workbook.getSheet("Sheet1");
                     Iterator<HSSFRow> rowIterator = sh.rowIterator();
                     %>
                     <table border="4">
                     <%
                     int rowcount=0;
                     System.out.println("xdgdsf");
                     while(rowIterator.hasNext()) {     
    
                         String user_id="";
                         String name="",email="";
                         String age="";
                        HSSFRow row = rowIterator.next();
                         Iterator<HSSFCell> cellIterator = row.cellIterator();
    
    
                         %><tr> <%
                         int colcount=0;
                         while(cellIterator.hasNext()) {
                             HSSFCell cell = cellIterator.next();
                             %><td><%
                             String value="";
                             int no=0;
                             switch(cell.getCellType()) {
                             case HSSFCell.CELL_TYPE_NUMERIC:
    
    
                                 System.out.print(cell.getNumericCellValue() + "\t\t");
                                 if((int) cell.getNumericCellValue()==0){
                                     no=0;
                                     }else{
                                         no=(int) cell.getNumericCellValue();
                                     }
                                 String column=mp.get(colcount+"");
                                 if(column.trim().equals("user_id")){
                                     out.print(cell.getNumericCellValue() + "\t\t");
                                     user_id=no+"";
                                 }else if(column.trim().equals("age")){
                                     out.print(cell.getNumericCellValue() + "\t\t");
                                     age=no+"";
                                 }
    
                                 break;
                                     case HSSFCell.CELL_TYPE_STRING:        
    
    
                                             System.out.print(cell.getStringCellValue().toString() + "\t\t");
                                             if(cell.getStringCellValue().toString()==null || cell.getStringCellValue().toString()=="" || cell.getStringCellValue().toString().trim().length()==0 ){
                                                 value="NA";
                                                 }else{
                                                     value=cell.getStringCellValue().toString();
                                                 }
                                             if(rowcount!=0){
                                                 column=mp.get(colcount+"");
                                               //  System.out.println(mp);
                                                if(column.trim().equals("name")){
                                                    out.print(cell.getStringCellValue().toString() + "\t\t");
                                                    name=value;
                                                }else if(column.trim().equals("email")){
                                                    out.print(cell.getStringCellValue().toString() + "\t\t");
                                                    email=value;
                                                }else  if(column.trim().equals("user_id")){
                                                 out.print(cell.getNumericCellValue() + "\t\t");
                                                 user_id=no+"";
                                             }else if(column.trim().equals("age")){
                                                 out.print(cell.getNumericCellValue() + "\t\t");
                                                 age=no+"";
                                             }
    
    
    
    
                                             }
                                             break;       
    
                             }  
                             if(rowcount==0){
                                 mp.put(colcount+"",cell.getStringCellValue().toString().trim());
                             }
                             colcount+=1;
                             %></td><%
                             }
                         System.out.println("\n");
                         rowcount+=1;
                         %></tr><%
                         if(rowcount!=0){
                             String query="insert into bulk_upload(user_id,name,email,age) values('"+user_id+"','"+name+"','"+email+"','"+age+"')";
                          System.out.println(query);
    
                             PreparedStatement ptmt=conn.prepareStatement(query);
    
                             int i=ptmt.executeUpdate();
    
                             if(i==1){
                              System.out.println("Updated ---------        ");
                             }else{
                             System.out.println("Not Updated ---------        "); 
                            }
                             ptmt.close();
    
    
    
                         }
                         conn.close();
    
                     %></table><%
                     }
    
    
            }   
    
    
        }catch(Exception e){
            e.printStackTrace();
            System.out.println(e);
        }
    
    
    %>
    </body>
    </html>
    
    在此处插入标题 名称:

    感谢u chandan提供的这段代码,我可以在这段代码中添加什么来将数据从excel发送到mysql数据库??我尝试了很多代码,但如果您试图存储在数据库中,mysql-connector-java-5.1.18-bin.jar就不起作用了。它不是强制性的,因此您应该修复您的程序,使其仅使用同一版本的POI JAR