要求做一个从网页上导入excel

来源:互联网 发布:淘宝 大类目小类目 编辑:程序博客网 时间:2024/05/01 04:12

网上文章,仅作学习之用,向作者表示感谢

 

要求做一个从网页上导入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"

 

 

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

 

二、上传excel的Servlet

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

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

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

 

 

1publicclass ImportExcelServlet extends HttpServlet {
2//缓冲区域
3  File tempPathFile;
4//默认路径
5  String uploadTo ="D:\\";
6// 支持的文件类型
7  String[] errorType = { ".xls" };
8//格式化日期
9  SimpleDateFormat format =new SimpleDateFormat("yyyyMMddHHmmssSSS");
10
11 @Override
12protectedvoid doGet(HttpServletRequest req, HttpServletResponse resp)
13throws ServletException, IOException {
14 req.setCharacterEncoding("utf-8");
15 resp.setCharacterEncoding("utf-8");
16 //取得服务器真实路径
17  uploadTo = req.getSession().getServletContext().getRealPath("\\") +"upload\\";
18// Create a factory for disk-based file items
19  DiskFileItemFactory factory =new DiskFileItemFactory();
20// 设置缓冲区大小,这里是4kb
21  factory.setSizeThreshold(4096);
22// 设置缓冲区目录
23  factory.setRepository(tempPathFile);
24// Create a new file upload handler
25  ServletFileUpload upload =new ServletFileUpload(factory);
26// Set overall request size constraint
27// 设置最大文件尺寸,这里是4MB
28 upload.setSizeMax(4*1024*1024); 
29// 开始读取上传信息
30 List fileItems =new ArrayList();
31try {
32 fileItems = upload.parseRequest(req);
33 } catch (FileUploadException e1) {
34 e1.printStackTrace();
35 }
36// 依次处理每个上传的文件
37 Iterator iter = fileItems.iterator();
38 System.out.println("fileItems的大小是"+ fileItems.size());
39// 正则匹配,过滤路径取文件名
40 String regExp =".+\\\\(.+)$";
41 Pattern p = Pattern.compile(regExp);
42while (iter.hasNext()) {
43 FileItem item = (FileItem) iter.next();
44// 忽略其他不是文件域的所有表单信息
45 System.out.println("正在处理"+ item.getFieldName());
46if (!item.isFormField()) {
47 String name = item.getName();
48long size = item.getSize();
49if ((name ==null|| name.equals("")) && size ==0)
50continue;
51 Matcher m = p.matcher(name);
52boolean result = m.find();
53if (result) {
54boolean flag =false;
55for (int temp =0; temp < errorType.length; temp++) {
56if(m.group(1).endsWith(errorType[temp])) {
57 flag =true;
58 }
59 }
60if(!flag) {
61 System.out.println("上传了不支持的文件类型");
62thrownew IOException(name +": wrong type");
63 }
64try {
65 String fileName = uploadTo + format.format(new Date()) + m.group(1).substring(m.group(1).indexOf("."));
66 item.write(new File(fileName));
67//调用ReadExcel类进行读出excel
68 ReadExcel.readExcel(fileName, resp.getWriter());
69 System.out.println(name +"\t\t"+ size);
70 } catch (Exception e) {
71 e.printStackTrace();
72 }
73 }
74 } else {
75// 这里添加对不是上传文件表单项的处理
76 System.out.println("这是一个表单项");
77 }
78 }
79
80 }
81
82 @Override
83protectedvoid doPost(HttpServletRequest req, HttpServletResponse resp)
84throws ServletException, IOException {
85 doGet(req, resp);
86 }
87
88 @Override
89publicvoid init() throws ServletException {
90 tempPathFile =new File("d:\\temp\\buffer\\");
91if (!tempPathFile.exists()) {
92 tempPathFile.mkdirs();
93 }
94 } 
95}
96

 

三、读出excel文件内容的类

 

1publicclass ReadExcel {
2
3publicstaticvoid readExcel(String pathname, PrintWriter out) {
4try {
5//打开文件
6 Workbook book = Workbook.getWorkbook(new File(pathname)) ;
7//取得第一个sheet
8 Sheet sheet = book.getSheet(0);
9//取得行数
10int rows = sheet.getRows();
11for(int i =0; i < rows; i++) {
12 Cell [] cell = sheet.getRow(i);
13for(int j=0; j<cell.length; j++) {
14//getCell(列,行)
15 out.print(sheet.getCell(j, i).getContents());
16 out.print("&nbsp;");
17 }
18 out.println("<br/>");
19 }
20//关闭文件
21 book.close();
22 } catch (BiffException e) {
23 e.printStackTrace();
24 } catch (IOException e) {
25 e.printStackTrace();
26 } 
27 }
28
29}
30

总结:上面只是一个很简单的导入excel文件的例子,如果想做完善还得下更多的功夫。在做的过程中如果出现Workbook打不开,请更换jxl版本,尽量用低版本,这样与jdk兼容会好点,我在做这个导入excel的时候,就遇到了版本兼容问题,处理了半天才发现问题所在。

原创粉丝点击