1. 程式人生 > >ajax上傳excel後讀出內容並無重新整理返回頁面

ajax上傳excel後讀出內容並無重新整理返回頁面

頁面程式碼

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
   
    <title>My JSP 'index.jsp' starting page</title>
 <meta http-equiv="pragma" content="no-cache">
 <meta http-equiv="cache-control" content="no-cache">
 <meta http-equiv="expires" content="0">   
 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
 <meta http-equiv="description" content="This is my page">
 <!--
 <link rel="stylesheet" type="text/css" href="styles.css">
 -->
 <link type="text/css" href="css/ui-lightness/jquery-ui-1.8.20.custom.css" rel="stylesheet" />
   <script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>
  <script type="text/javascript" src="js/jquery-ui-1.8.20.custom.min.js"></script>
  <script type="text/javascript" src="js/json.js"></script>
 <script type="text/javascript">
 
 //這裡被呼叫的回撥函式,並負責將返回來的資料全部填充到頁面上
    function backCallUpload(ArryStr){
      var dataTable=document.getElementById("dataTable");
       var str;
       str="<tr><td><input type='checkbox'></td></tr><tr><td>";
       if(ArryStr&&ArryStr.length&&ArryStr.length>0){
         for(var i=0;i<ArryStr.length;i++){
         var tempObj=ArryStr[i];
           str+=tempObj.name;
          var newRow = dataTable.insertRow();
   var oCell = newRow.insertCell();
      oCell.innerHTML = "<input type='checkbox' name='t1'>";
      var oCell1 = newRow.insertCell();
      oCell1.innerHTML = tempObj.name;
   
          
                str+="</td></tr>";
               
                if(i!=ArryStr.length-1){
                str+="<tr><td><input type='checkbox'></td></tr><tr><td>";
                }
           //TODO: implent add those value.
         }
       }
     
     
  


    }
   
    function createTr(){
      var trOjb=document.createElement("tr");
      return trOjb;
    }
   
    function createTd(){
      var tdOjb=document.createElement("td");
      return tdOjb;
    }
   
    function createInput(){
       var inputOjb=document.createElement("input");
        return inputOjb;
    }
 </script>
  </head>
 
  <body>
    <h1>subm匯入Excel</h1>
<hr>

<form action="importExcel" method="post" enctype="multipart/form-data" target="hidden_frame">
<input type="file" name="importExcel" id="importExcel">

<input type="submit" value="匯入" id='submit'>
<br/>


<table id='dataTable' border='1'>
     <tr>
      <th><input type="checkbox"></th>
      <th>Name</th>
     </tr>
     <tr>
      <td><input type="checkbox"></td>
      <td>ansel</td>
     </tr>
    </table>
   
     <iframe name='hidden_frame' id="hidden_frame" src="MyJsp.jsp" style='display:none'></iframe>  
  </body>
</html>

package com.test;


import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import com.url.ajax.json.JSONArray;
import com.url.ajax.json.JSONObject;

public class PoiReadXls2 extends HttpServlet {


 
 File tempPathFile;
 // 預設路徑
 String uploadTo = "D:\\";
 // 支援的檔案型別
 String[] errorType = { ".xls" };
 // 格式化日期
 SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSSS");
 @Override
 protected void doPost(HttpServletRequest req, HttpServletResponse resp)
   throws ServletException, IOException {
  // TODO Auto-generated method stub
  req.setCharacterEncoding("utf-8");
  resp.setCharacterEncoding("utf-8");
  // 取得伺服器真實路徑
  uploadTo = req.getSession().getServletContext().getRealPath("\\")
    + "upload\\";
  DiskFileItemFactory factory = new DiskFileItemFactory();
  // 設定緩衝區大小,這裡是4kb
  factory.setSizeThreshold(4096);
  // 設定緩衝區目錄
  factory.setRepository(tempPathFile);
  // Create a new file upload handler
  ServletFileUpload upload = new ServletFileUpload(factory);
  // Set overall request size constraint
  // 設定最大檔案尺寸,這裡是4MB
  upload.setSizeMax(4 * 1024 * 1024);
  // 開始讀取上傳資訊
  List fileItems = new ArrayList();
  
  try {
   fileItems = upload.parseRequest(req);
  } catch (FileUploadException e1) {
   e1.printStackTrace();
  }
  // 依次處理每個上傳的檔案
  Iterator iter = fileItems.iterator();
  System.out.println("fileItems的大小是" + fileItems.size());
  // 正則匹配,過濾路徑取檔名
  String regExp = ".+\\\\(.+)$";
  Pattern p = Pattern.compile(regExp);
  
  while (iter.hasNext()) {
   FileItem item = (FileItem) iter.next();
   // 忽略其他不是檔案域的所有表單資訊
   System.out.println("正在處理" + item.getFieldName());
   if (!item.isFormField()) {
    String name = item.getName();
    long size = item.getSize();
    if ((name == null || name.equals("")) && size == 0)
     continue;
    Matcher m = p.matcher(name);
    boolean result = m.find();
    if (result) {
     boolean flag = false;
     for (int temp = 0; temp < errorType.length; temp++) {
      if (m.group(1).endsWith(errorType[temp])) {
       flag = true;
      }
     }
     if (!flag) {
      System.out.println("上傳了不支援的檔案型別");
      throw new IOException(name + ": wrong type");
     }
     try {
      String fileName = uploadTo + format.format(new Date())
        + m.group(1).substring(m.group(1).indexOf("."));
      item.write(new File(fileName));
      File f = new File(fileName);
      try {
       FileInputStream is = new FileInputStream(f);
       HSSFWorkbook wbs = new HSSFWorkbook(is);
       HSSFSheet childSheet = wbs.getSheetAt(0);
       // System.out.println(childSheet.getPhysicalNumberOfRows());
       System.out.println("有行數" + (childSheet.getLastRowNum()+1));
       JSONObject json = new JSONObject();  
       JSONArray members = new JSONArray();  
       String transferValue="[";
       for (int j = 0; j < childSheet.getLastRowNum()+1; j++) {
        HSSFRow row = childSheet.getRow(j);
        // System.out.println(row.getPhysicalNumberOfCells());
        // System.out.println("有列數" + row.getLastCellNum());
        if (null != row) {
         for (int k = 0; k < row.getLastCellNum(); k++) {
          HSSFCell cell = row.getCell((short) k);
          if (null != cell) {
           switch (cell.getCellType()) {
           case HSSFCell.CELL_TYPE_NUMERIC: // 數字
            System.out.print(cell.getNumericCellValue()
              + "   ");
            break;
           case HSSFCell.CELL_TYPE_STRING: // 字串
            System.out.print(cell.getStringCellValue()
              + "   ");
            JSONObject member = new JSONObject()  
                     .put("name", cell.getStringCellValue());
            members.put(j, member);  
            transferValue+="{name:'"+cell.getStringCellValue()+"'}";
            if(j!=childSheet.getLastRowNum())
            {
             transferValue+=",";
            }
            break;
           case HSSFCell.CELL_TYPE_BOOLEAN: // Boolean
            System.out.println(cell.getBooleanCellValue()
              + "   ");
            break;
           case HSSFCell.CELL_TYPE_FORMULA: // 公式
            System.out.print(cell.getCellFormula() + "   ");
            break;
           case HSSFCell.CELL_TYPE_BLANK: // 空值
            System.out.println(" ");
            break;
           case HSSFCell.CELL_TYPE_ERROR: // 故障
            System.out.println(" ");
            break;
           default:
            System.out.print("未知型別   ");
            break;
           }
          } else {
           System.out.print("-   ");
          }
         }
        }
        System.out.println();
       }
//       json.put("names", members);  
//       System.out.println(json.toString());  
//       resp.getWriter().print(json);
       transferValue+="]";
       //這個地方尤為重要,呼叫頁面上的回撥函式
       String processParentFunctionStr="parent.backCallUpload("+transferValue+")";
       PrintWriter writer=resp.getWriter();
       resp.setContentType("text/html");
       resp.setCharacterEncoding("utf-8");
       System.out.println("<script>"+processParentFunctionStr+"</script>");
       writer.write("<script>"+processParentFunctionStr+"</script>");
      } catch (Exception e) {
       e.printStackTrace();
      }
      System.out.println(name + "\t\t" + size);
     } catch (Exception e) {
      e.printStackTrace();
     }
    }
   } else {
    // 這裡新增對不是上傳檔案表單項的處理
    System.out.println("這是一個表單項");
   }
  }
  
 }

 @Override
 protected void doGet(HttpServletRequest req, HttpServletResponse resp)
   throws ServletException, IOException {
  // TODO Auto-generated method stub


 }

 @Override
 protected void doHead(HttpServletRequest req, HttpServletResponse resp)
   throws ServletException, IOException {
  // TODO Auto-generated method stub
  super.doHead(req, resp);
 }

 public static void main(String[] args) {
  File f = new File("D:\\myfile1.xls");
  try {
   FileInputStream is = new FileInputStream(f);
   HSSFWorkbook wbs = new HSSFWorkbook(is);
   HSSFSheet childSheet = wbs.getSheetAt(0);
   // System.out.println(childSheet.getPhysicalNumberOfRows());
   System.out.println("有行數" + (childSheet.getLastRowNum()+1));
   for (int j = 0; j < childSheet.getLastRowNum()+1; j++) {
    HSSFRow row = childSheet.getRow(j);
    // System.out.println(row.getPhysicalNumberOfCells());
    // System.out.println("有列數" + row.getLastCellNum());
    if (null != row) {
     for (int k = 0; k < row.getLastCellNum(); k++) {
      HSSFCell cell = row.getCell((short) k);
      if (null != cell) {
       switch (cell.getCellType()) {
       case HSSFCell.CELL_TYPE_NUMERIC: // 數字
        System.out.print(cell.getNumericCellValue()
          + "   ");
        break;
       case HSSFCell.CELL_TYPE_STRING: // 字串
        System.out.print(cell.getStringCellValue()
          + "   ");
        break;
       case HSSFCell.CELL_TYPE_BOOLEAN: // Boolean
        System.out.println(cell.getBooleanCellValue()
          + "   ");
        break;
       case HSSFCell.CELL_TYPE_FORMULA: // 公式
        System.out.print(cell.getCellFormula() + "   ");
        break;
       case HSSFCell.CELL_TYPE_BLANK: // 空值
        System.out.println(" ");
        break;
       case HSSFCell.CELL_TYPE_ERROR: // 故障
        System.out.println(" ");
        break;
       default:
        System.out.print("未知型別   ");
        break;
       }
      } else {
       System.out.print("-   ");
      }
     }
    }
    System.out.println();
   }
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
}