要求做一个从网页上导入excel
要求做一個(gè)從網(wǎng)頁(yè)上導(dǎo)入excel,,開始著手去實(shí)現(xiàn)它。
思路很簡(jiǎn)單:
1、做一個(gè)jsp頁(yè)面,頁(yè)面包括瀏覽文件,提交文件
2、將excel文件上傳到服務(wù)器
3、? 服務(wù)器對(duì)該excel文件進(jìn)行讀出
4、? 將excel文件內(nèi)容顯示到頁(yè)面上
?
環(huán)境搭建:
需要準(zhǔn)備的包:commons-fileupload-1.2.1.jar & commons-io-1.3.2.jar 這兩個(gè)包是上傳用的
jxl.jar 這個(gè)包是讀取excel用的 下載地址 :http://sourceforge.net/projects/jexcelapi/? 建議不要用新版本,因?yàn)樾掳姹緯?huì)出現(xiàn)與jdk版本兼容問題,如果運(yùn)行程序出現(xiàn)問題的時(shí)候請(qǐng)切換舊版本。
?
一、Jsp頁(yè)面
注意:1、在jsp頁(yè)面的form要使用html本身的<form>標(biāo)記,而不要使用第三方視圖開源框架的form標(biāo)記,例如不要使用strut的<htm:form>。
2、在<form>的屬性里必須加上? ENCTYPE="multipart/form-data"
1 <h1>導(dǎo)入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="導(dǎo)入">
6 </form>
二、上傳excel的Servlet
注意:1、導(dǎo)入的excel最好用后綴為.xls,如果用.xlsx可能會(huì)導(dǎo)不進(jìn)去。
2、在調(diào)用FileItem的write方法前必須保證文件的存放路徑存在否則出現(xiàn)異常。commons fileupload不會(huì)自動(dòng)為你建立不存在的目錄。
3、上傳后會(huì)對(duì)文件進(jìn)行重命名,以時(shí)間為文件名進(jìn)行命名
1 public class Import ExcelServlet extends HttpServlet {2 //緩沖區(qū)域
3 File tempPathFile;
4 //默認(rèn)路徑
5 String uploadTo ="D:\\";
6 // 支持的文件類型
7 String[] errorType = { ".xls" };
8 //格式化日期
9 SimpleDateFormat format =new SimpleDateFormat("yyyyMMddHHmmssSSS");
10 @Override
11 protected void doGet(HttpServletRequest req, HttpServletResponse resp)
12 throws ServletException, IOException
13 {
14 req.setCharacterEncoding("utf-8");
15 resp.setCharacterEncoding("utf-8");
16 //取得服務(wù)器真實(shí)路徑
17 uploadTo = req.getSession().getServletContext().getRealPath("\\") +"upload\\";
18 // Create a factory for disk-based file items
19 DiskFileItemFactory factory =new DiskFileItemFactory();
20 // 設(shè)置緩沖區(qū)大小,這里是4kb
21 factory.setSizeThreshold(4096);
22 // 設(shè)置緩沖區(qū)目錄
23 factory.setRepository(tempPathFile);
24 // Create a new file upload handler
25 ServletFileUpload upload =new ServletFileUpload(factory);
26 // Set overall request size constraint
27 // 設(shè)置最大文件尺寸,這里是4MB
28 upload.setSizeMax(4*1024*1024);
29 // 開始讀取上傳信息
30 List fileItems =new ArrayList();
31 try
32 {
33 fileItems = upload.parseRequest(req);
34 }
35 catch (FileUploadException e1)
36 {
37 e1.printStackTrace();
38 }
39 // 依次處理每個(gè)上傳的文件
40 Iterator iter = fileItems.iterator();
41 System.out.println("fileItems的大小是"+ fileItems.size());
42 // 正則匹配,過濾路徑取文件名
43 String regExp =".+\\\\(.+)$";
44 Pattern p = Pattern.compile(regExp);
45 while (iter.hasNext())
46 {
47 FileItem item = (FileItem) iter.next();
48 // 忽略其他不是文件域的所有表單信息
49 System.out.println("正在處理"+ item.getFieldName());
50 if (!item.isFormField())
51 {
52 String name = item.getName();
53 long size = item.getSize();
54 if ((name ==null|| name.equals("")) && size ==0)
55 continue;
56 Matcher m = p.matcher(name);
57 boolean result = m.find();
58 if (result)
59 {
60 boolean flag =false;
61 for (int temp =0; temp < errorType.length; temp++)
62 {
63 if(m.group(1).endsWith(errorType[temp]))
64 {
65 flag =true;
66 }
67 }
68 if(!flag)
69 {
70 System.out.println("上傳了不支持的文件類型");
71 thrownew IOException(name +": wrong type");
72 }
73 try {
74 String fileName = uploadTo + format.format(new Date()) + m.group(1).substring(m.group(1).indexOf("."));
75 item.write(new File(fileName));
76 //調(diào)用ReadExcel類進(jìn)行讀出excel
77 ReadExcel.readExcel(fileName, resp.getWriter());
78 System.out.println(name +"\t\t"+ size);
79 }
80 catch (Exception e)
81 {
82 e.printStackTrace();
83 }
84 }
85 }
86 else
87 {
88 // 這里添加對(duì)不是上傳文件表單項(xiàng)的處理
89 System.out.println("這是一個(gè)表單項(xiàng)");
90 }
91 }
92 }
93 @Override
94 protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
95 {
96 doGet(req, resp);
97 }
98 @Override
99 public void init() throws ServletException
100 {
101 tempPathFile =new File("d:\\temp\\buffer\\");
102 if (!tempPathFile.exists())
103 {
104 tempPathFile.mkdirs();
105 }
106 }
107 }
三、讀出excel文件內(nèi)容的類
1 public class ReadExcel2 {
3 public staticvoid readExcel(String pathname, PrintWriter out)
4 {
5 try {
6 //打開文件
7 Workbook book = Workbook.getWorkbook(new File(pathname)) ;
8 //取得第一個(gè)sheet
9 Sheet sheet = book.getSheet(0);
10 //取得行數(shù)
11 int rows = sheet.getRows();
12 for(int i =0; i < rows; i++)
13 {
14 Cell [] cell = sheet.getRow(i);
15 for(int j=0; j<cell.length; j++)
16 {
17 //getCell(列,行)
18 System.out.print(sheet.getCell(j, i).getContents());
19 System.out.print(" ");
20 }
21 System.out.println("<br/>");
22 }
23 //關(guān)閉文件
24 book.close();
25 }
26 catch (BiffException e)
27 {
28 e.printStackTrace();
29 }
30 catch (IOException e)
31 {
32 e.printStackTrace();
33 }
34 }
轉(zhuǎn)載于:https://www.cnblogs.com/ayan/archive/2011/12/30/2308042.html
總結(jié)
以上是生活随笔為你收集整理的要求做一个从网页上导入excel的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Think in Java之斐波那契数列
- 下一篇: Introduce Null Objec