Java实现导入Excel jxl方式

               

上班的时候公司要求做一个从网页上导入excel,研究了半天后,开始着手去实现它。

思路很简单:

1、做一个jsp页面,页面包括浏览文件,提交文件

2、将excel文件上传到服务器

3、  服务器对该excel文件进行读出

4、  将excel文件内容显示到页面上

 

环境搭建:

需要准备的包:commons-fileupload-1.2.1.jar & commons-io-1.3.2.jar 这两个包是上传用的

jxl.jar 这个包是读取excel用的 下载地址 :http://sourceforge.net/projects/jexcelapi/  建议不要用新版本,因为新版本会出现与jdk版本兼容问题,如果运行程序出现问题的时候请切换旧版本。

 

一、Jsp页面

注意:1、在jsp页面的form要使用html本身的<form>标记,而不要使用第三方视图开源框架的form标记,例如不要使用strut的<htm:form>。

   2、在<form>的属性里必须加上  ENCTYPE="multipart/form-data"

<h1>导入Excel</h1>       <hr>       <form action="importExcel" method="post" enctype="multipart/form-data">           <input type="file" name="importExcel" id="importExcel">           <input type="submit" value="导入">        </form>

二、上传excel的Servlet

注意:1、导入的excel最好用后缀为.xls,如果用.xlsx可能会导不进去。

2、在调用FileItem的write方法前必须保证文件的存放路径存在否则出现异常。commons fileupload不会自动为你建立不存在的目录。

3、上传后会对文件进行重命名,以时间为文件名进行命名

public class ImportExcelServlet extends HttpServlet {     //缓冲区域      File tempPathFile;     //默认路径      String uploadTo = "D:\\";     // 支持的文件类型      String[] errorType = { ".xls" };     //格式化日期      SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSSS");      @Override     protected void doGet(HttpServletRequest req, HttpServletResponse resp)             throws ServletException, IOException {         req.setCharacterEncoding("utf-8");         resp.setCharacterEncoding("utf-8");  //取得服务器真实路径          uploadTo = req.getSession().getServletContext().getRealPath("\\") + "upload\\";         // Create a factory for disk-based file items          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)); //调用ReadExcel类进行读出excel                         ReadExcel.readExcel(fileName, resp.getWriter());                         System.out.println(name + "\t\t" + size);                     } catch (Exception e) {                         e.printStackTrace();                     }                 }             } else {                 // 这里添加对不是上传文件表单项的处理                 System.out.println("这是一个表单项");             }         }      }      @Override     protected void doPost(HttpServletRequest req, HttpServletResponse resp)             throws ServletException, IOException {         doGet(req, resp);     }      @Override     public void init() throws ServletException {         tempPathFile = new File("d:\\temp\\buffer\\");         if (!tempPathFile.exists()) {             tempPathFile.mkdirs();         }     }     }

三、读出excel文件内容的类

public class ReadExcel {      public static void readExcel(String pathname, PrintWriter out) {         try {             //打开文件             Workbook book = Workbook.getWorkbook(new File(pathname)) ;             //取得第一个sheet             Sheet sheet = book.getSheet(0);             //取得行数             int rows = sheet.getRows();             for(int i = 0; i < rows; i++) {                 Cell [] cell = sheet.getRow(i);                 for(int j=0; j<cell.length; j++) {                     //getCell(列,行)                     out.print(sheet.getCell(j, i).getContents());                     out.print(" ");                 }                 out.println("<br/>");             }             //关闭文件             book.close();         } catch (BiffException e) {             e.printStackTrace();         } catch (IOException e) {             e.printStackTrace();         }      }      }


总结:上面只是一个很简单的导入excel文件的例子,如果想做完善还得下更多的功夫。在做的过程中如果出现Workbook打不开,请更换jxl版本,尽量用低版本,这样与jdk兼容会好点,我在做这个导入excel的时候,就遇到了版本兼容问题,处理了半天才发现问题所在。所以想做这个例子给大家参考,以后不要犯和我同样的错误。O(∩_∩)O哈哈~

           

再分享一下我老师大神的人工智能教程吧。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.csdn.net/jiangjunshow

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值