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

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

 

要求做一个从网页上导入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、上传后会对文件进行重命名,以时间为文件名进行命名

 

 

1 public class 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
12 protected void doGet(HttpServletRequest req, HttpServletResponse resp)
13 throws 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();
31 try {
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);
42 while (iter.hasNext()) {
43 FileItem item = (FileItem) iter.next();
44 //  忽略其他不是文件域的所有表单信息
45 System.out.println("正在处理"+ item.getFieldName());
46 if (!item.isFormField()) {
47 String name = item.getName();
48 long size = item.getSize();
49 if ((name == null|| name.equals("")) && size ==0)
50 continue;
51 Matcher m = p.matcher(name);
52 boolean result = m.find();
53 if (result) {
54 boolean flag = false;
55 for ( int temp =0; temp < errorType.length; temp++) {
56 if(m.group(1).endsWith(errorType[temp])) {
57 flag = true;
58 }
59 }
60 if(!flag) {
61 System.out.println("上传了不支持的文件类型");
62 throw new IOException(name +": wrong type");
63 }
64 try {
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
83 protected void doPost(HttpServletRequest req, HttpServletResponse resp)
84 throws ServletException, IOException {
85 doGet(req, resp);
86 }
87
88 @Override
89 public void init()  throws ServletException {
90 tempPathFile = new File("d:\\temp\\buffer\\");
91 if (!tempPathFile.exists()) {
92 tempPathFile.mkdirs();
93 }
94 } 
95}
96

 

三、读出excel文件内容的类

 

1 public class ReadExcel {
2
3 public static void readExcel(String pathname, PrintWriter out) {
4 try {
5 // 打开文件
6 Workbook book = Workbook.getWorkbook( new File(pathname)) ;
7 // 取得第一个sheet
8 Sheet sheet = book.getSheet(0);
9 // 取得行数
10 int rows = sheet.getRows();
11 for( int i =0; i < rows; i++) {
12 Cell [] cell = sheet.getRow(i);
13 for( 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的时候,就遇到了版本兼容问题,处理了半天才发现问题所在。

  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值