上傳excel檔案到伺服器
阿新 • • 發佈:2019-02-16
最近遇到了需要上傳excel檔案,並將excel表中的資料都出來,存到資料庫中的需求,今天將步驟整理一下,如下:
一、新建一個html(或jsp頁面),如:uploadExcel.html,程式碼如下:
<html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>匯入Excel表</title> <meta http-equiv="Content-Type" content="text/html; charset=gbk"> </head> <body class="dialogBody"> <div> <form id="form2" method="post" action="../../uploadExcel" enctype="multipart/form-data" style="align: center"> <table width="100%" border="0" cellspacing="0" cellpadding="6" class="blockTable"> <tr> <td> </td> </tr> <tr> <td align="center"><h2>選擇Excel表:</h2></td> <td align="center"> <div> <input type="file" name="file_upload" /> </div> </td> </tr> <tr> <td align="center"><input type="submit" name="submit" value="上傳" /></td> </tr> <tr></tr> <tr></tr> <tr></tr> </table> </form> </div> </body> </html>
2、在web.xml中配置servlet和servlet-mapping,程式碼如下:
<servlet> <servlet-name>uploadExcel</servlet-name> <servlet-class>com.shop.upload.UploadServlet</servlet-class> <init-param> <param-name>filePath</param-name> <param-value>store</param-value> </init-param> <init-param> <param-name>tempFilePath</param-name> <param-value>temp</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>uploadExcel</servlet-name> <url-pattern>/uploadExcel</url-pattern> </servlet-mapping>
3、servlet類程式碼如下:
package com.upload; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.servlet.ServletConfig; 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.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; /** * 上傳檔案的servlet類 */ public class UploadServlet extends HttpServlet{ /** * @function:Excel 表格上傳 */ private String filePath; //存放上傳檔案的目錄 private String tempFilePath;//存放臨時檔案的目錄 @Override public void init(ServletConfig config) throws ServletException { super.init(config); //讀取初始化引數filePath filePath=config.getInitParameter("filePath"); //讀取初始化引數tempFilePath tempFilePath=config.getInitParameter("tempFilePath"); filePath=getServletContext().getRealPath(filePath); tempFilePath=getServletContext().getRealPath(tempFilePath); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html; charset=GBK"); response.setHeader("Cache-Control", "no-cache"); response.setCharacterEncoding("GBK"); PrintWriter out = response.getWriter(); try { //建立一個基於硬碟的FileItem工廠 DiskFileItemFactory factory=new DiskFileItemFactory(); //設定向硬碟寫資料時所用的緩衝區的大小,暫定10M,一會再改 factory.setSizeThreshold(1000*1024); //設定臨時目錄 factory.setRepository(new File(tempFilePath)); //建立一個檔案上傳處理器 ServletFileUpload upload=new ServletFileUpload(factory); //設定允許上傳的檔案的最大尺寸,暫定10M,一會再改 upload.setSizeMax(1000*1024); Map<String, String> params = new HashMap<String, String>();// 存放請求引數 List<FileItem> items=upload.parseRequest(request); Iterator iter=items.iterator(); while(iter.hasNext()){ FileItem item=(FileItem) iter.next(); if(item.isFormField()){ processFormField(item,params); //處理普通的表單域 }else{ processUploadFile(item,params); //處理上傳檔案 } } String path=params.get("path"); int total=getExcelTotal(path); out.println("<h1 align=\"center\">點選'確認'按鈕繼續</h1>"); out.flush(); out.close(); } catch (Exception e) { e.printStackTrace(); out.println("<h1 align=\"center\">上傳出錯--點選'取消'按鈕</h1>"); out.flush(); out.close(); } } /** * 獲得excel中資料總數 * @param path * @return */ public int getExcelTotal(String path) { final Sheet sheet; final Workbook book; int total=0; try { // t.xls為要讀取的excel檔名 book = new VillageHouses().getWorkBookObject(path) ; // 獲得第一個工作表物件(ecxel中sheet的編號從0開始,0,1,2,3,....) sheet = book.getSheetAt(0) ; total = sheet.getLastRowNum() ; } catch (Exception e) { e.printStackTrace(); } return total; } /** * 處理上傳檔案 * @param item * @param params * @throws IOException */ private void processUploadFile(FileItem item, Map<String, String> params) throws IOException { createFileDirectory(filePath); String fileName = item.getName() ; String fileType = fileName.substring(fileName.lastIndexOf("."), fileName.length()); long time = System.currentTimeMillis();// 時間毫秒數 String savePath = filePath +"/"+ time + fileType; System.out.println("伺服器檔案路徑:"+savePath); InputStream inputStream = item.getInputStream();// 獲取檔案流 FileOutputStream outputStream = new FileOutputStream(savePath);// 建立輸出流 byte[] tyte = new byte[1024]; int len = 0; while ((len = inputStream.read(tyte)) > 0) { outputStream.write(tyte, 0, len); } inputStream.close(); outputStream.close(); item.delete();// 刪除臨時檔案 params.put("path", savePath); } /** * 處理表單資料 * @param item * @param params */ private void processFormField(FileItem item, Map<String, String> params) { String name=item.getFieldName();//獲得表單域的名字 String value=item.getString(); //獲得表單域的值 if("xqid".equals(name)) params.put("xqid", value); if("id".equals(name)) params.put("id", value); } /** * 判斷專案所在伺服器上的資料夾是否建立 * @param path */ private void createFileDirectory(String path) { File file = new File(path); if (!file.exists()) { // 建立資料夾 file.mkdirs(); } } }
這個就是jsp負責頁面,servlet負責實現具體的上傳功能,程式碼中有標註,很簡單,應該都可以看懂