当前位置: 首页 > 知识库问答 >
问题:

使用POI在jsp中上传读取excel文件

丌官积厚
2023-03-14

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

图书馆

  1. commons-fileupload-1.2.2.jar
  2. commons-io-2.1.jar

索引.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>

UploadServlet.java(Servlet)

import java.io.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;

public class UploadFile extends HttpServlet{

String saveFile="D:/upload/"; 

protected void processRequest(...)throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();

try {
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(Exception e){
}
Iterator itr = items.iterator();
while(itr.hasNext()){
FileItem item = (FileItem)itr.next();
if(item.isFormField()){

}else{
String itemname = item.getName();
if((itemname==null || itemname.equals(""))){
continue;
}
String filename = FilenameUtils.getName(itemname);
File f = checkExist(filename);
item.write(f);
}
}
}

}catch(Exception e){

}
finally {
out.close();
}
}

private File checkExist(String fileName) {
File f = new File(saveFile+"/"+fileName);

if(f.exists()){
StringBuffer sb = new StringBuffer(fileName);
sb.insert(sb.lastIndexOf("."),"-"+new Date().getTime());
f = new File(saveFile+"/"+sb.toString());
}
return f;
}

@Override
protected void doGet(...)throws ServletException, IOException {
processRequest(request, response);

}

@Override
protected void doPost(...)throws ServletException, IOException {
processRequest(request, response);
}

@Override
public String getServletInfo() {
return "Short description";
}

}

然后,我创建了一个新的JAVA项目(SWING ),并尝试通过POI读取EXCEL文件的代码,它也工作正常,下面是代码:

图书馆

  1. dom4j-1.6.1.jar
  2. poi-3.10-FINAL-20140208.jar
  3. poi-ooxml-3.9-20121203.jar
  4. poi-ooxml-schemas-3.9-20121203.jar
  5. 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();
}
}
}

问题是如何混合这两个代码,以便上传文件,然后将数据从EXCEL打印到JSP中的一个表中????帮帮我,我在这个程序上耽搁了一个多月

共有2个答案

姬天宇
2023-03-14
<%@ 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>

user_id和剩余年龄应为整数应为字符串

阿布夫代码是针对 java 1.5 只接受 xls 文件而不是 xlsx,库是

commons-fileupload-1.3.jar-mysql-connector-java-5.1.18-bin。jar org.apache.commons.io网站。jar poi-2.5.1-final-20040804.jar

储承
2023-03-14

item.write(f)之后;添加此

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

从此处继续您的代码

 类似资料:
  • 我正在使用我的android应用程序中的Apache POI读取存储在SDCard中的xlsx文件。我正在使用Apache POI中的以下jar库 poi-ooxml-schemas-3.9-20121203.jar POI-OOXML-3.9-20121203.jar 有人能说出我在哪里失踪了吗?

  • 我正在写一些代码导入Excel文件到数据库。文件可能很大(数千行),所以我使用事件API。POI版本为3.9 我这样打开文件:FileInputStream fin=new FileInputStream(file); 有些文件在最后一行引发FileNotFoundException。的确,如果我用7zip打开那些文件,就没有条目,而是有。 可以在Excel2007中成功打开相同的文件。当我用手动

  • 我创建了此代码以使用Apache POI读取excel文件的内容。我使用eclipse作为编辑器,但当我运行代码时,我的粗体行出现问题。有什么问题?excel的内容如下:

  • 我试图使用Apache POI读取.xlsx格式的excel文件。下面给出了我的代码。 我使用跟随jar来运行这段代码。commons-codec-1.9.jar,dom4j-1.6.jar,poi-3.11-beta2-20140822.jar,poi-ooxml-3.11-beta2-20140822.jar,poi-ooxml-schemas-3.11-beta2-20140822.jar,

  • 问题内容: 我正在尝试在Java中阅读excel。我有以下代码。 我导入了poi.3.6jar和poi.ooxml-3.6 jar。当我运行该程序时,出现以下错误消息。 我不明白为什么会出现此错误消息。请帮助我。 问题答案: 将文件添加到您的类路径。

  • 问题内容: 我正在尝试读取(使用apache poi).xlsx文件,该文件不在文件系统中,但在类路径中。我正在使用Maven-因此它位于资源文件夹中。 我的代码是- 我收到此例外。 当我从文件系统读取同一文件时,一切都很好。我的代码中有错误吗?还是想念一些东西? UPDATE1:这是在Web应用程序中,因此代码已部署在tomcat 7中。 UPDATE2:当我以这种方式读取同一文件时,它可以工作