jsp中導入導出excel,ssh框架

導入Excel:jsp中java

1 <form action="user_importTradingMoney" enctype="multipart/form-data" method="post">
2 <label>導入數據
3             <input type="file" name="tradingMoneyFile" value="選擇文件">
4             <input type="submit" value="提交數據">
5             </label>
6 </form>


action中:app

action最前面確定要有下面這幾句,並且要有其對應的set、get方法jsp

private File tradingMoneyFile;// 實際上傳文件
private String tradingMoneyFileContentType; // 文件的內容類型
private String tradingMoneyFileFileName; // 上傳文件名

 這是爲了經過struts2自動得到上傳的文件,固然struts.xml中確定要有這幾句:工具

1 <constant name="struts.i18n.reload" value="true" />
2     <constant name="struts.configuration.xml.reload" value="true" />
3     <constant name="struts.devMode" value="true" />
4     <constant name=" struts.action.extension" value="action,," />
5     <constant name="struts.multipart.maxSize" value="102400000000000" />

文件大小什麼的設定本身看着辦。。。。post

而後action中的importTradingMoney方法以下:this

 1 //導入交易金額的Excel表
 2     public String importTradingMoney(){
 3         HttpServletRequest request = ServletActionContext.getRequest();
 4         Calendar cal = Calendar.getInstance();
 5         int month = cal.get(Calendar.MONTH);
 6         int year = cal.get(Calendar.YEAR);
 7          jxl.Workbook wb=null;
 8          try {
 9             //InputStream is=new FileInputStream(tradingMoneyFile);//讀取存放數據的excel表格在電腦中的路徑
10             InputStream is=new FileInputStream(tradingMoneyFile);
11             wb =Workbook.getWorkbook(is);//建立workbook對象,個人理解就是這個整個的excel
12             Sheet s=wb.getSheet(0);//建立sheet,其實就是excel中的每一頁,其中的每一張表,他的下標是從0開始的//這裏也就是取得第一張表
13             int rsRows=s.getRows();//獲得全部的行
14             int rsColumns=s.getColumns();//獲得全部的列
15             for(int i=1;i<rsRows;i++){
16                 String userName=s.getCell(0, i).getContents();//(列,行)
17                 int tradingMoney=Integer.parseInt(s.getCell(1, i).getContents().toString());
18                                 TradingMoney tradingMoneyClass=new TradingMoney();
19                 tradingMoneyClass.setUserName(userName);
20                 tradingMoneyClass.setTradingMoney(tradingMoney);
21                 tradingMoneyClass.setYear(year);
22                 tradingMoneyClass.setMonth(month);
23                 userService.addTradingMoney(tradingMoneyClass);
24             }
25         } catch (FileNotFoundException e) {
26             // TODO Auto-generated catch block
27             e.printStackTrace();
28         } catch (BiffException e) {
29             // TODO Auto-generated catch block
30             e.printStackTrace();
31         } catch (IndexOutOfBoundsException e) {
32             // TODO Auto-generated catch block
33             e.printStackTrace();
34         } catch (IOException e) {
35             // TODO Auto-generated catch block
36             e.printStackTrace();
37         } catch (Exception e) {
38             // TODO Auto-generated catch block
39             e.printStackTrace();
40         }
41          List<User> userList = null;
42         try {
43             userList = userService.selectUser(null, null);
44         } catch (Exception e) {
45             // TODO Auto-generated catch block
46             e.printStackTrace();
47         }
48         request.setAttribute("userList", userList);
49         return "selectUser";
50     }

至於excel的導出,我只是簡單地把當前頁面複製到了excel中:spa

1 <%@page import="java.text.SimpleDateFormat"%>  
2   <%
3       SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd");
4       String filename = new String(("佣金明細-"+sf.format(new Date())).getBytes("utf8"),"ISO-8859-1"); 
5       response.setHeader("Content-disposition","attachment; filename="+filename+".xls"); 
6   %>


由於我要複製a.jsp頁面的內容到excel中,而a.jsp中的內容又是便利list而出來,若是直接把上面這段代碼加入到a.jsp中,那麼a.jsp中的內容你就會看不到,這個頁面一打開就會讓你下載,因此就沒有那種先預覽再下載的效果了。。。。因此就在a.jsp中加了一個按鈕excel

1 <input type="button" value="結果導出爲Excel" style="width:120px" class="button-action" onclick="toExcel(<s:property value='#request.owerUser.id' />,'${request.owerUser.userAccount }')"/>
1 var userIdvar,userAccountvar;
2         function toExcel(userIdvar,userAccountvar){
3 //腳本運行後,將在新窗體newwindow中打開,寬爲100,高爲400,距屏頂0象素,屏左0象素,無工具條,無菜單條,無滾動條,不可調整大小,無地址欄,無狀態欄。
4 window.open('reportUser_selectDetailReportUser?notice=1&userId='+userIdvar+'&userAccount='+userAccountvar,'newwindow','height=600,width=1200,top=80,left=80,toolbar=no,menubar=no,scrollbars=yes, resizable=yes,location=no, status=no');
5         };

就是從新發一遍請求到b.jsp中,其內容與a.jsp相同,因此這個b.jsp就不須要打開了。。。一切ok!code

 

 

剛剛新增了不是簡單地copy頁面,而是從action導出excel表:orm

  1 //導出Excel表
  2     public void exportForm(){
  3         HttpServletRequest request = ServletActionContext.getRequest();
  4         try {
  5         request.setCharacterEncoding("utf8");
  6 
  7         Date now = new Date();
  8         SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
  9         String sDate = sdf.format(now);
 10         String fileName = new String(("用戶-"+sDate).getBytes("utf8"),"ISO-8859-1"); 
 11         String file = fileName+".xls";
 12 
 13         HttpServletResponse response = ServletActionContext.getResponse();
 14         response.setContentType("application/vnd.ms-excel");
 15         response.setHeader("Content-Disposition" ,"attachment;filename="+file+"");
 16         OutputStream os = response.getOutputStream();
 17         String[] title = {"姓名","帳號","角色","電話","郵箱","發展人帳號","備註"};
 18         int i=0;
 19 
 20         WritableWorkbook wwb = Workbook.createWorkbook(os);
 21         WritableSheet ws = wwb.createSheet("用戶表", 0);
 22         ws.setColumnView(0,15);
 23         ws.setColumnView(1,15);
 24         ws.setColumnView(2,20);
 25         ws.setColumnView(3,15);
 26         ws.setColumnView(4,18);
 27         ws.setColumnView(5,15);
 28         ws.setColumnView(6,35);
 29         ws.setColumnView(7,15);
 30         
 31 
 32         for( i=0;i<title.length;i++){
 33               WritableFont wf = new WritableFont(WritableFont.TIMES, 11, WritableFont.BOLD, false);
 34               WritableCellFormat wcfF = new WritableCellFormat(wf);
 35               Label labelCF = new Label(i, 0, title[i],wcfF);
 36               ws.addCell(labelCF);
 37         }
 38 
 39         i=1;
 40         String  userName = null;
 41         String  userAccount = null;
 42         String  userRole = null;
 43         String  userPhone = null;
 44         String  userEmail = null;
 45         String  higherAgentAccount = null;
 46         String  userNote = null;
 47 
 48         //根據selectedIds,生成一個List
 49 
 50 
 51         //List list = this.pageBean.getList();
 52 
 53         List list = userService.selectUser(null, null);
 54         Iterator it  = list.iterator(); // 得到一個迭代子
 55 
 56         while (it.hasNext()) {
 57             User v = (User)it.next(); // 獲得下一個元素
 58                             
 59             userName = v.getUserName();
 60             Label labelC0 = new Label(0,i,userName);
 61             ws.addCell(labelC0);
 62     
 63             userAccount = v.getUserAccount();
 64             Label labelC1 = new Label(1,i,userAccount);
 65             ws.addCell(labelC1);
 66     
 67             userRole = v.getRole().getRoleName();
 68             Label labelC2 = new Label(2,i,userRole);
 69             ws.addCell(labelC2);
 70     
 71     
 72             userPhone = v.getUserPhone();
 73             Label labelC3 = new Label(3,i,userPhone);
 74             ws.addCell(labelC3);
 75     
 76             userEmail = v.getUserEmail();
 77             Label labelC4 = new Label(4,i,userEmail);
 78             ws.addCell(labelC4);
 79     
 80             higherAgentAccount = v.getHigherAgentAccount();
 81             Label labelC5 = new Label(5,i,higherAgentAccount);
 82             ws.addCell(labelC5);
 83     
 84             userNote = v.getUserNote();
 85             Label labelC6 = new Label(6,i,userNote);
 86             ws.addCell(labelC6);
 87     
 88             i++;   
 89         }
 90         //寫入Exel工做表
 91         os.flush();
 92            wwb.write();
 93            //關閉Excel工做薄對象
 94            wwb.close();
 95         os.close();
 96         } catch (Exception e) {
 97 
 98         e.printStackTrace();
 99         }
100     }

 

//若是想打開並寫入一個已經存在的excel,只能經過副本操做
//Excel得到文件 
Workbook wb2=Workbook.getWorkbook(excelFile); 
//打開一個文件的副本,而且指定數據寫回到原文件 
WritableWorkbook wwb2= Workbook.createWorkbook(excelFile,wb2); 
WritableSheet ws = wwb2.getSheet(0);
相關文章
相關標籤/搜索