web-dev-qa-db-ja.com

Upload +はPOIを使用してjspでExcelファイルを読み取ります

私はJSPでExcelファイルを読みたいので、このために最初にファイルを:Dパーティションのフォルダーにアップロードしましたploadsという名前のWebアプリケーションプロジェクトを使用して、私は-read Excelがアップロードしたファイル別のJava projet .両方のコードが機能している。ここに、Webアプリケーションプロジェクトを介して特定のフォルダーにアップロードするコードがあります( JSPおよびSERVLET):

ライブラリ

  1. commons-fileupload-1.2.2.jar
  2. 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>

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

問題はこれらの2つのコードを混合する方法ファイルをアップロードして、ExcelからJSPのテーブルにデータを印刷できるようにするためです????この手順で1か月以上行き詰っています

8
Nihad KH

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

ここからコードを続けます。

4
Chandan Reddy
<%@ 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とAgeは整数でなければなりません。残りはStringである必要があります

abouveコードはJava= 1.5の場合、xlsxではなくxlsファイルのみを受け入れ、ライブラリは

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

1
Chickenturtle