java使用POI上傳Excel

來源:互聯網
上載者:User

JSP

<%@ page language="java" import="java.util.*" pageEncoding="gb2312"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>   <script type=text/javascript src="./js/upload.js"></script>    <title>My JSP 'index.jsp' starting page</title>  </head>  <body>    <form name="form" action="Path" method="post" enctype="multipart/form-data">        檔案:<javascript><input type="file" name="excel"/></javascript>        <input type="text" name="123">        <input type="submit" value="提交"/>    </form>  </body></html>

Servlet

package com....;import java.io.File;import java.io.IOException;import java.util.List;import java.util.UUID;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.FileUploadException;import org.apache.commons.fileupload.disk.DiskFileItemFactory;import org.apache.commons.fileupload.servlet.ServletFileUpload;import com.;public class Path extends HttpServlet {    public Path() {        super();    }    public void destroy() {        super.destroy();    }    public void doPost(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {//      String path = request.getServletPath();//      String p = request.getSession().getServletContext().getRealPath("/");        //建立檔案項工廠        //ExcelUploadConnector euc = new ExcelUploadConnector();        ReadExcel r= new ReadExcel();        DiskFileItemFactory factory = new DiskFileItemFactory();        //建立解析資料請求項        ServletFileUpload upload = new ServletFileUpload(factory);        try {            //開始解析            List<FileItem> list = upload.parseRequest(request);            for(int i=0;i<list.size();i++){      //從列表中遍曆每一個檔案                FileItem item = list.get(i);                if(item.isFormField()){                    //輸出表單欄位值                    System.out.println(new String(item.getString().getBytes("ISO-8859-1"),"utf-8"));                }else{                    //處理檔案                    String fileName = item.getName();                    System.out.println("file:"+fileName);                    //擷取副檔名                    String extName = fileName.substring(fileName.lastIndexOf("."));                    System.out.println("extName:"+extName);                    //產生UUID檔案名稱                    String newName = UUID.randomUUID().toString();                    String rootPath = getServletContext().getRealPath("\\upload");                    System.out.println(rootPath);                    String newPath = rootPath+"/"+newName+extName;                    System.out.println(newPath);                    item.write(new File(newPath));                    //euc.ConnectorDatabase(newPath);                    r.readExcelFile(newPath);                }            }        } catch (FileUploadException e) {            e.printStackTrace();        } catch (Exception e) {            e.printStackTrace();        }    }    public void init() throws ServletException {    }}

Java

package com....;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;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...;/* * @describe 通過路徑擷取Excel檔案,並將Excel檔案資料傳入DAO * @author zhutianpeng * */public class ReadExcel {                                                                                                               Map<Integer,String> map = new HashMap<Integer,String>();    List<Map<Integer,String>> list = new ArrayList<Map<Integer,String>>();    HSSFWorkbook workbook;//  ConnectorA a = new ConnectorA();                                                                                                               public void readExcelFile(String filePath){        try {            FileInputStream excelFile = new FileInputStream(filePath);            workbook = new HSSFWorkbook(excelFile);            //讀入Excel檔案的第一個表            HSSFSheet sheet = workbook.getSheetAt(0);            //從檔案第二行開始讀取,第一行為標識行            for(int i=1;i<=sheet.getLastRowNum();i++){                System.out.println("行數:"+sheet.getPhysicalNumberOfRows());                HSSFRow row = sheet.getRow(i);                if(row==null){                    continue;                }                for(int j=1;j<=row.getPhysicalNumberOfCells();j++){                    if(row.getCell(j)!=null){                        // 注意:一定要設成這個,否則可能會出現亂碼//                      row.getCell(j).setEncoding(HSSFCell.ENCODING_UTF_16);                        String str = getCellValue(row.getCell(j));                        map.put(j,str);                    }                }                UploadExcelImpl ue = new UploadExcelImpl();                ue.uploadExcel(map);                map.clear();            }        } catch (FileNotFoundException e) {            e.printStackTrace();            System.out.println("【Excel路徑有誤,請重新確認Excel路徑...】");        } catch (IOException e) {            e.printStackTrace();            System.out.println("【檔案輸入有誤,請重新確定您要加入的檔案...】");        }    }                                                                                                               //傳入cell的值,進行cell實值型別的判斷,並返回String類型     private static String getCellValue(HSSFCell cell){            String value = null;            //簡單的查檢列類型            System.out.println("cell.getCellType():"+cell.getCellType());            switch(cell.getCellType())  {                                                                                                                                       case HSSFCell.CELL_TYPE_STRING://字串                    System.out.println("HSSFCell.CELL_TYPE_STRING:"+HSSFCell.CELL_TYPE_STRING);                    value = cell.getRichStringCellValue().toString();                    break;                case HSSFCell.CELL_TYPE_NUMERIC://數字                    System.out.println("HSSFCell.CELL_TYPE_NUMERIC:"+HSSFCell.CELL_TYPE_NUMERIC);                    long dd = (long)cell.getNumericCellValue();                    value = dd+"";                    break;                case HSSFCell.CELL_TYPE_BLANK:                    System.out.println("HSSFCell.CELL_TYPE_BLANK:"+HSSFCell.CELL_TYPE_BLANK);                    value = "";                    break;                   case HSSFCell.CELL_TYPE_FORMULA:                    System.out.println("HSSFCell.CELL_TYPE_FORMULA:"+HSSFCell.CELL_TYPE_FORMULA);                    value = String.valueOf(cell.getCellFormula());                    break;                case HSSFCell.CELL_TYPE_BOOLEAN://boolean型值                    System.out.println("HSSFCell.CELL_TYPE_BOOLEAN:"+HSSFCell.CELL_TYPE_BOOLEAN);                    value = String.valueOf(cell.getBooleanCellValue());                    break;                case HSSFCell.CELL_TYPE_ERROR:                    System.out.println("HSSFCell.CELL_TYPE_ERROR:"+HSSFCell.CELL_TYPE_ERROR);                    value = String.valueOf(cell.getErrorCellValue());                    break;                default:                    System.out.println("default");                    break;            }            return value;        }}

注意:

   1、JSP頁面Form表單中的 enctype="multipart/form-data" 是必須使用的,將表單中的內容以流的形式進行轉寄。    2、上傳過程是必須將使用者本地機的內容上傳至伺服器後才能進行相應的操作。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.