1

 1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
 2 <%@ taglib prefix="s" uri="/struts-tags" %>
 3 
 4 <html >
 5 <head>
 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
 7 </head>
 8 
 9 <body>
10     <!-- <a href="emp_report.action?empId=0007" target="_blank">report</a>
11     <s:form action="emp_report.action">
12         <s:textfield name="empId"/>
13         <s:submit value="确定"/>
14     </s:form>-->
15     <script type="text/javascript">
16         var empDetailPanel = new EmpDetailPanel();
17         var w = Ext.getCmp('mainTab').getActiveTab().getInnerWidth();
18         var h = Ext.getCmp('mainTab').getActiveTab().getInnerHeight();
19         var activeTab = Ext.getCmp('empDetailPanelId');
20         if(activeTab){
21             activeTab.setHeight(h);
22             activeTab.setWidth(w);
23         }
24         //渲染
25         activeTab.render('empDetail');
26     </script>
27     <div id="empDetail"></div>
28 </body>
29 </html>
30  

 

 

2.

  1 //创建一个员工个人信息面板
  2 EmpDetailPanel = Ext.extend(Ext.Panel,{
  3     id: 'empDetailPanelId',
  4     constructor: function(){
  5         EmpDetailPanel.superclass.constructor.call(this, {
  6             items: [{
  7                 html: '<iframe src="" id="viewArea" width="100%" height="500" frameborder="0" scrolling="auto"></iframe>'
  8             }],
  9             tbar: new Ext.Toolbar({
 10                 items: ['员工工号',{
 11                     xtype: 'textfield',
 12                     id: 'report_empId',
 13                     width: 100,
 14                     listeners: {'blur': blurFn2}
 15                 },{
 16                     text: '详细PDF单个预览',
 17                     handler: this.viewFn
 18                 },'-',{
 19                     text: '简单PDF单个预览',
 20                     handler: this.simpleViewFn    
 21                 },'-',{
 22                     text: '详细PDF单个导出',
 23                     handler: this.exportFn
 24                 },'-',{
 25                     text: '详细PDF全部导出',
 26                     handler: this.exportAllFn
 27                 },'-',{
 28                     text: '简单PDF导出',
 29                     handler: this.simplePdfExportFn
 30                 },'-',{
 31                     text: '简单PDF全部导出',
 32                     handler: this.simplePdfAllExportFn
 33                 },'-',{
 34                     text: '详细Excel全部导出',
 35                     handler: this.detailXlsAllExportFn
 36                 }]
 37             })
 38         })
 39     },
 40     //详细PDF单个预览
 41     viewFn: function(){
 42         var url = 'emp_detailPdfReport.action?empId=';
 43         var empId = Ext.get('report_empId').dom.value;
 44         if(empId == ''){
 45             Ext.Msg.alert('提示','请输入工号');
 46             return;
 47         }
 48         //更改Src属性刷新页面
 49         Ext.get('viewArea').dom.src = url+empId;
 50     },
 51     //简单PDF单个预览
 52     simpleViewFn: function(){
 53         var url = 'emp_simplePdfReport.action?empId=';
 54         var empId = Ext.get('report_empId').dom.value;
 55         if(empId == ''){
 56             Ext.Msg.alert('提示','请输入工号');
 57             return;
 58         }
 59         Ext.get('viewArea').dom.src = url+empId;
 60     },
 61     //详细PDF单个导出
 62     exportFn: function(){
 63         var empId = Ext.get('report_empId').dom.value;
 64         if(empId == ''){
 65             Ext.Msg.alert('提示','请输入工号');
 66             return;
 67         }
 68         document.location = 'emp_detailPdfExport.action?empId='+empId;
 69     },
 70     //详细PDF全部导出
 71     exportAllFn: function(){
 72         document.location = 'emp_detailPdfExport.action?empId=all';
 73     },
 74     //简单PDF导出
 75     simplePdfExportFn : function(){
 76         var empId = Ext.get('report_empId').dom.value;
 77         if(empId == ''){
 78             Ext.Msg.alert('提示','请输入工号');
 79             return;
 80         }
 81         document.location = 'emp_simplePdfExport.action?empId='+empId;
 82     },
 83     //简单PDF全部导出
 84     simplePdfAllExportFn: function(){
 85         document.location = 'emp_simplePdfExport.action?empId=all';
 86     },
 87     //详细Excel全部导出
 88     detailXlsAllExportFn: function(){
 89         document.location = 'emp_detailXlsExport.action';
 90     }
 91 });
 92 //焦点离开
 93     blurFn2 = function(value){
 94         var empId = value.getRawValue();
 95         Ext.Ajax.request({
 96             url: 'emp_isExist.action',
 97             method: 'post',
 98             params: {
 99                 empId: empId
100             },
101             success: isExistSuccessFn2,
102             failure: save_failure
103         })
104     };
105     //焦点离开成功
106     isExistSuccessFn2 = function(response, options){
107         if(response.responseText == ''){
108             Ext.Msg.alert('提示','此工号不存在');
109         }
110     }

 

 

3.员工个人信息Action

  1 package com.hrmsys.action;
  2 
  3 import java.io.File;
  4 import java.io.IOException;
  5 import java.io.PrintWriter;
  6 import java.io.UnsupportedEncodingException;
  7 import java.util.ArrayList;
  8 import java.util.List;
  9 
 10 import javax.servlet.http.HttpServletResponse;
 11 
 12 import org.apache.struts2.ServletActionContext;
 13 
 14 import com.hrmsys.bean.EmployeeBean;
 15 import com.hrmsys.model.Employee;
 16 import com.hrmsys.model.User;
 17 import com.hrmsys.service.EmpService;
 18 import com.hrmsys.service.JobChangeService;
 19 import com.hrmsys.util.ConditionValidate;
 20 import com.hrmsys.util.CurrentDate;
 21 import com.hrmsys.util.FileExport;
 22 import com.hrmsys.util.SequenceBuilder;
 23 import com.opensymphony.xwork2.ActionContext;
 24 
 25 public class EmpAction extends BaseAction{
 26     private EmpService empService;
 27     private Employee emp;
 28     private List<EmployeeBean> empBeans;
 29     private JobChangeService jobChangeService;
 30     /**
 31      * 由于dept和job常用,故单独成一js文件
 32      * 但在与struts整合时不便将属性名绑定到name,
 33      * 故此单独定义deptId和jobId属性
 34      */
 35     private String deptId = null;
 36     private String jobId  = null;
 37     private String empPhoto = null;
 38     /**
 39      * 配置文件中的参数会通过setter方法注入
 40      * rePath获取savePath的值
 41      */
 42     private String rePath = null;
 43     /**
 44      * 查询条目
 45      */
 46     private String condition;
 47     /**
 48      * 查询内容
 49      */
 50     private String conditionValue;
 51     /**
 52      * 保存的路径
 53      */
 54     private String savePath; 
 55     /**
 56      * 上传的文件内容 
 57      */
 58     private File upload;
 59     /**
 60      * 保存的文件名
 61      */
 62     private String uploadFileName;
 63     /**
 64      * 上传的文件种类
 65      */
 66     private String uploadContentType;
 67     private String empId;
 68     private String ids;
 69     private String start;
 70     private String limit;
 71     
 72     /************方法**********************************************/
 73     /**
 74      * 清单
 75      */
 76     public void list(){
 77         String json = null;
 78         json = empService.getByHQL(deptId, condition, conditionValue, start, limit);
 79         this.setStart(null);
 80         this.setLimit(null);
 81         this.out(json);
 82     }
 83     /**
 84      * 保存员工信息
 85      */
 86     public void save(){
 87         log.info("save start....");
 88         log.info(this.getEmpPhoto());
 89         String msg = "保存失败";
 90         HttpServletResponse response = this.getResponse();
 91         User user = (User)ActionContext.getContext().getSession().get("user");
 92         emp.setEmpPhoto(this.getEmpPhoto());
 93         emp.setEmpAddDate(CurrentDate.getDate());
 94         emp.setEmpAddPerson(user.getUserName());
 95         msg = empService.save(emp);
 96         this.out("{success: true, msg: '"+msg+"'}");
 97     }
 98     /**
 99      * 员工头像上传
100      */
101     public void upload(){
102         log.info("upload start...");
103         log.info("uploadFileName="+this.getUploadFileName());
104         //重命名
105         String fileName = SequenceBuilder.getSequence()+this.getUploadFileName().substring(this.getUploadFileName().indexOf(".")); 
106         String msg = empService.uploadPhoto(this.getSavePath()+"\\"+fileName, this.getUpload());
107         this.out("{success: true, msg: '"+msg+"', path: '"+this.rePath+"/"+fileName+"'}");
108     }
109     /**
110      * 根据工号判断是否存在此员工
111      */
112     public void isExist(){
113         String empName = empService.isExistByEmpId(empId);
114         this.out(empName);
115     }
116     
117     public void unique(){
118         String emp = empService.unique(empId);
119         this.out(emp);
120     }
121     
122     public void delete(){
123         String filePath = ServletActionContext.getRequest().getRealPath(savePath);
124         String msg = empService.delete(ids, filePath);
125         this.out("{success: true, msg: '"+msg+"'}");
126     }
127     
128     public void intoUpdate(){
129         String empJson = empService.listByEmpId(empId);
130         this.out(empJson);
131     }
132     /**
133      * 详细员工pdf报表预览
134      */
135     public String detailPdfReport(){
136         empBeans = empService.getEmpList(empId);
137         return "detailPdf";
138     }
139     public String simplePdfReport(){
140         empBeans = empService.getEmpList(empId);
141         return "simplePdf";
142     }
143     /**
144      * 导出详细报表pdf
145      */
146     public void detailPdfExport(){
147         empService.pdfExport(empId, this.getResponse(),"员工详细信息.pdf","detailEmp.jasper");
148     }
149     /**
150      * 导出员工简单信息pdf
151      */
152     public void simplePdfExport(){
153         empService.pdfExport(empId, this.getResponse(),"员工简单信息.pdf", "simpleEmp.jasper");
154     }
155     /**
156      * 导出员工简单信息Excel
157      */
158     public void detailXlsExport(){
159         empService.xlsExport(this.getResponse(), "员工信息.xls");
160     }
161     /*********getter and setter ***********/
162     public EmpService getEmpService() {
163         return empService;
164     }
165 
166     public void setEmpService(EmpService empService) {
167         this.empService = empService;
168     }
169 
170     public String getDeptId() {
171         return deptId;
172     }
173 
174     public void setDeptId(String deptId) {
175         this.deptId = deptId;
176     }
177 
178     public String getCondition() {
179         return condition;
180     }
181 
182     public void setCondition(String condition) {
183         this.condition = condition;
184     }
185 
186     public String getConditionValue() {
187         return conditionValue;
188     }
189 
190     public void setConditionValue(String conditionValue) {
191         this.conditionValue = conditionValue;
192     }
193 
194     public Employee getEmp() {
195         return emp;
196     }
197 
198     public void setEmp(Employee emp) {
199         this.emp = emp;
200     }
201     public String getJobId() {
202         return jobId;
203     }
204     public void setJobId(String jobId) {
205         this.jobId = jobId;
206     }
207     public String getSavePath() {
208         //struts.xml中配置savePath参数,且获取文件夹的真实地址
209         return ServletActionContext.getRequest().getRealPath(savePath);
210     }
211     public void setSavePath(String savePath) {
212         this.rePath = savePath;
213         this.savePath = savePath;
214     }
215     public File getUpload() {
216         return upload;
217     }
218     public void setUpload(File upload) {
219         this.upload = upload;
220     }
221     public String getUploadFileName() {
222         return uploadFileName;
223     }
224     public void setUploadFileName(String uploadFileName) {
225         this.uploadFileName = uploadFileName;
226     }
227     public String getUploadContentType() {
228         return uploadContentType;
229     }
230     public void setUploadContentType(String uploadContentType) {
231         this.uploadContentType = uploadContentType;
232     }
233     public String getEmpPhoto() {
234         return empPhoto;
235     }
236     public void setEmpPhoto(String empPhoto) {
237         this.empPhoto = empPhoto;
238     }
239     public JobChangeService getJobChangeService() {
240         return jobChangeService;
241     }
242     public void setJobChangeService(JobChangeService jobChangeService) {
243         this.jobChangeService = jobChangeService;
244     }
245     public String getEmpId() {
246         return empId;
247     }
248     public void setEmpId(String empId) {
249         this.empId = empId;
250     }
251     public String getIds() {
252         return ids;
253     }
254     public void setIds(String ids) {
255         this.ids = ids;
256     }
257     public List<EmployeeBean> getEmpBeans() {
258         return empBeans;
259     }
260     public void setEmpBeans(List<EmployeeBean> empBeans) {
261         this.empBeans = empBeans;
262     }
263     public String getStart() {
264         return start;
265     }
266     public void setStart(String start) {
267         this.start = start;
268     }
269     public String getLimit() {
270         return limit;
271     }
272     public void setLimit(String limit) {
273         this.limit = limit;
274     }
275     
276 }

 

 

5.

 1 package com.hrmsys.service;
 2 
 3 import java.io.File;
 4 import java.util.List;
 5 
 6 import javax.servlet.http.HttpServletResponse;
 7 
 8 import com.hrmsys.bean.EmployeeBean;
 9 import com.hrmsys.model.Department;
10 import com.hrmsys.model.Employee;
11 
12 public interface EmpService {
13     /**
14      * 按部门编号查询部门总人数
15      * @param deptId
16      * @return
17      */
18     int findNumByDept(Department dept);
19     /**
20      * 获取所有员工信息
21      * @return 以json形式返回
22      */
23     String getAll(String start, String limit);
24     /**
25      * 按部门获取员工信息
26      * @return 以json形式返回
27      */
28     String findByDeptId(String deptId);
29     /**
30      * 按条件查询员工表
31      * @param deptId 部门ID
32      * @param condition 查询条目
33      * @param conditionValue 查询内容
34      * @return 返回Json.toString()
35      */
36     String getByHQL(String deptId, String condition, String conditionValue, String start, String limit);
37     /**
38      * 保存员工信息
39      * @param emp
40      */
41     String save(Employee emp);
42     /**
43      * 图片上传处理
44      * @param savePath 保存的位置
45      * @param upload 上传的文件
46      * @return msg返回结果
47      */
48     String uploadPhoto(String savePath, File upload);
49     /**
50      * 判断员工是否存在
51      * @param empId
52      * @return
53      */
54     String isExistByEmpId(String empId);
55     /**
56      * 删除
57      * @param ids
58      * @return
59      */
60     String delete(String ids, String filePath);
61     /**
62      * 按empId查询
63      * @param empId
64      * @return
65      */
66     String listByEmpId(String empId);
67     
68     /**
69      * 导员工pdf信息
70      * @param empId
71      */
72     void pdfExport(String empId, HttpServletResponse response, String filename, String jasper);
73     List<EmployeeBean> getEmpList(String empId);
74     /**
75      * 导出Excel
76      * @param response
77      * @param string
78      * @param string2
79      */
80     void xlsExport(HttpServletResponse response, String filename);
81     
82     String unique(String empId);
83 }

 

 

 

6.

  1 package com.hrmsys.service.impl;
  2 
  3 import java.io.File;
  4 import java.io.FileInputStream;
  5 import java.io.FileNotFoundException;
  6 import java.io.FileOutputStream;
  7 import java.io.IOException;
  8 import java.util.ArrayList;
  9 import java.util.List;
 10 
 11 import javax.servlet.http.HttpServletResponse;
 12 
 13 import net.sf.json.JSONArray;
 14 
 15 import com.hrmsys.bean.EmployeeBean;
 16 import com.hrmsys.bean.PageBean;
 17 import com.hrmsys.dao.EmployeeDAO;
 18 import com.hrmsys.enums.StaticValue;
 19 import com.hrmsys.model.Department;
 20 import com.hrmsys.model.Employee;
 21 import com.hrmsys.service.EmpService;
 22 import com.hrmsys.util.ConditionValidate;
 23 import com.hrmsys.util.FileExport;
 24 
 25 public class EmpServiceImpl implements EmpService {
 26 
 27     private EmployeeDAO empDAO;
 28 
 29     @Override
 30     public int findNumByDept(Department dept) {
 31         List<Employee> emps = empDAO.findByDept(dept);
 32         if (emps != null)
 33             return emps.size();
 34         return 0;
 35     }
 36 
 37     public EmployeeDAO getEmpDAO() {
 38         return empDAO;
 39     }
 40 
 41     public void setEmpDAO(EmployeeDAO empDAO) {
 42         this.empDAO = empDAO;
 43     }
 44 
 45     @Override
 46     public String getAll(String start, String limit) {
 47         List<Employee> emps = empDAO.findAll(Integer.parseInt(start), Integer.parseInt(limit));
 48         String json = null;
 49         if (emps.size() != 0) {
 50             json = JSONArray.fromObject(emps).toString();
 51         }
 52         int totalProperty = empDAO.findTotal(Employee.class);
 53         return "{totalProperty:"+totalProperty+",root:"+json+"}";
 54     }
 55 
 56     @Override
 57     public String findByDeptId(String deptId) {
 58         Department dept = new Department();
 59         dept.setDeptId(deptId);
 60         List<Employee> emps = empDAO.findByDept(dept);
 61         String json = JSONArray.fromObject(emps).toString();
 62         return json;
 63     }
 64 
 65     @Override
 66     public String getByHQL(String deptId, String condition,
 67             String conditionValue, String start, String limit) {
 68         
 69         PageBean pageBean = empDAO.findByHQL(deptId, condition,
 70                 conditionValue, Integer.parseInt(start), Integer.parseInt(limit));
 71         String json = JSONArray.fromObject(pageBean.getRoot()).toString();
 72         return "{totalProperty:"+pageBean.getTotalProperty()+",root:"+json+"}";
 73     }
 74 
 75     @Override
 76     public String save(Employee emp) {
 77         if (empDAO.saveOrUpdate(emp)) {
 78             return StaticValue.SAVE_SUCCESS;
 79         }
 80         return StaticValue.SAVE_FAILURE;
 81     }
 82 
 83     @Override
 84     public String uploadPhoto(String savePath, File upload) {
 85         boolean flag = true;
 86         String msg = null;
 87         try {
 88             FileOutputStream fos = new FileOutputStream(savePath);
 89             FileInputStream fis = new FileInputStream(upload);
 90             byte[] buffer = new byte[1024];
 91             int len = 0;
 92             while ((len = fis.read(buffer)) > 0) {
 93                 fos.write(buffer, 0, len);
 94             }
 95         } catch (FileNotFoundException e) {
 96             flag = false;
 97             e.printStackTrace();
 98         } catch (IOException e) {
 99             flag = false;
100             e.printStackTrace();
101         } finally {
102             if (flag) {
103                 msg = StaticValue.UPLOAD_SUCCESS;
104             } else {
105                 msg = StaticValue.UPLOAD_FAILURE;
106             }
107         }
108         return msg;
109     }
110 
111     @Override
112     public String isExistByEmpId(String empId) {
113         Employee emp = empDAO.findByEmpId(empId);
114         if(null != emp){
115             return emp.getEmpName();
116         }
117         return "";
118     }
119 
120     @Override
121     public String unique(String empId) {
122         Employee emp = empDAO.findByEmpId(empId);
123         if(null != emp){
124             return JSONArray.fromObject(emp).toString();
125         }
126         return "";
127     }
128     
129     @Override
130     public String delete(String ids, String filePath) {
131         String[] empIds = ids.split(",");
132         for(String empId : empIds){
133             Employee emp = empDAO.findByEmpId(empId);
134             String urlPath = emp.getEmpPhoto();
135             if(urlPath.indexOf("default.gif") < 0){ //默认图片不删除 
136                 int position = urlPath.lastIndexOf("/");
137                 File file=new File(filePath +"\\"+ urlPath.substring(position, urlPath.length()));
138                  if(file.exists() && file.isFile())
139                   file.delete();
140             }
141         }
142         if(empDAO.deleteByEmpId(empIds)){
143             return StaticValue.DELETE_SUCCESS;
144         }
145         return StaticValue.DELETE_FAILURE;
146     }
147 
148     @Override
149     public String listByEmpId(String empId) {
150         Employee emp = empDAO.findByEmpId(empId);
151         return JSONArray.fromObject(emp).toString();
152     }    
153 
154     public List<EmployeeBean> packageEmp(List<Employee> emps) {
155         List<EmployeeBean> empBeans = new ArrayList<EmployeeBean>();
156         for(Employee emp : emps){
157             EmployeeBean empBean = new EmployeeBean();
158             empBean.setEmpAccount(emp.getEmpAccount());
159             empBean.setEmpAddress(emp.getEmpAddress());
160             empBean.setEmpBank(emp.getEmpBank());
161             empBean.setEmpBirth(emp.getEmpBirth());
162             empBean.setEmpEducation(emp.getEmpEducation());
163             empBean.setEmpEmail(emp.getEmpEmail());
164             empBean.setEmpId(emp.getEmpId());
165             empBean.setEmpIdcard(emp.getEmpIdcard());
166             empBean.setEmpMobilephone(emp.getEmpMobilephone());
167             empBean.setEmpName(emp.getEmpName());
168             empBean.setEmpNation(emp.getEmpNation());
169             empBean.setEmpNationality(emp.getEmpNation());
170             empBean.setEmpOrigin(emp.getEmpOrigin());
171             empBean.setEmpPhoto(emp.getEmpPhoto());
172             empBean.setEmpPost(emp.getEmpPost());
173             empBean.setEmpProfession(emp.getEmpProfession());
174             empBean.setEmpQq(emp.getEmpQq());
175             empBean.setEmpSchool(emp.getEmpSchool());
176             if(emp.getEmpSex() == 1){
177                 empBean.setEmpSex("男");
178             }else{
179                 empBean.setEmpSex("女");
180             }
181             empBean.setEmpTelephone(emp.getEmpTelephone());
182             empBean.setJob(emp.getJob().getJobName());
183             empBean.setDept(emp.getDepartment().getDeptName());
184             empBeans.add(empBean);
185         }
186     
187         return empBeans;
188     }
189 
190     @Override
191     public void pdfExport(String empId, HttpServletResponse response, String filename, String jasper) {
192         Employee emp = null;
193         List<Employee> emps = new ArrayList<Employee>();
194         if(!"all".equals(empId) && ConditionValidate.isEmpty(empId)){
195             emp = empDAO.findByEmpId(empId);
196             emps.add(emp);
197         }else{
198             emps = empDAO.findAll(Employee.class);
199         }
200         List<EmployeeBean> empBeans = packageEmp(emps);
201         FileExport fileExport = new FileExport();
202         fileExport.exportPDF(empBeans, filename,jasper, response);
203         
204     }
205 
206     @Override
207     public List<EmployeeBean> getEmpList(String empId) {
208         List<Employee> emps = new ArrayList<Employee>();
209         Employee emp = empDAO.findByEmpId(empId);
210         emps.add(emp);
211         return this.packageEmp(emps);
212     }
213 
214     @Override
215     public void xlsExport(HttpServletResponse response, String filename) {
216         List<Employee> emps = empDAO.findAll(Employee.class);
217         List<EmployeeBean> empBeans = this.packageEmp(emps);
218         FileExport fileExport = new FileExport();
219         fileExport.exportXls(empBeans, filename, response);
220     }
221 
222 }

 

 

8.

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
 3 <struts>
 4     <constant name="struts.i18n.encoding" value="UTF-8"/>
 5     <constant name="struts.devMode" value="false"/>
 6     <package name="default" extends="struts-default,jasperreports-default" namespace="/">
 7         <global-results >
 8             <result name="input">error.jsp</result>
 9         </global-results>
10         
11         <action name="user_*" class="userAction" method="{1}">
12             <result name="success" type="redirect">jsp/main.jsp</result>
13             <result name="input">index.jsp</result>
14             <result name="exit" type="redirect">index.jsp</result>
15         </action>
16         <action name="menu" class="menuAction" method="load"></action>
17         <action name="dept_*" class="deptAction" method="{1}"></action>
18         <action name="job_*" class="jobAction" method="{1}"></action>
19         <action name="emp_*" class="empAction" method="{1}">
20             <param name="savePath">photo</param>
21             <result name="detailPdf" type="jasper">
22                 <param name="location">jasperreport/detailEmp.jasper</param>
23                 <param name="dataSource">empBeans</param>
24                 <param name="format">PDF</param>
25             </result>
26             <result name="simplePdf" type="jasper">
27                 <param name="location">jasperreport/simpleEmp.jasper</param>
28                 <param name="dataSource">empBeans</param>
29                 <param name="format">PDF</param>
30             </result>
31         </action>
32         <action name="jobChange_*" class="jobChangeAction" method="{1}"></action>
33         <action name="rec_*" class="recruitmentAction" method="{1}"></action>
34         <action name="train_*" class="trainAction" method="{1}"></action>
35         <action name="tRecord_*" class="tRecordAction" method="{1}"></action>
36         <action name="ePunish_*" class="ePunishAction" method="{1}"></action>
37         <action name="revenue_*" class="revenueAction" method="{1}"></action>
38         <action name="boon_*" class="boonAction" method="{1}"></action>
39         <action name="salBasic_*" class="salaryBasicAction" method="{1}"></action>
40         <action name="salary_*" class="salaryAction" method="{1}">
41             <result name="salView" type="jasper">
42                 <param name="location">jasperreport/salary.jasper</param>
43                 <param name="dataSource">salBeans</param>
44                 <param name="format">PDF</param>
45             </result>
46         </action>
47         <action name="permission_*" class="permissionAction" method="{1}"></action>
48         <action name="role_*" class="roleAction" method="{1}"></action>
49         <action name="rolePer_*" class="rolePermissionAction" method="{1}"></action>
50         <action name="recruitment_*" class="recruitmentAction" method="{1}"></action>
51         <action name="*">
52             <result>{1}.jsp</result>
53         </action>
54     </package>
55 </struts>    

 

 

8.

  1 package com.hrmsys.util;
  2 
  3 import java.io.File;
  4 import java.io.IOException;
  5 import java.io.UnsupportedEncodingException;
  6 import java.util.List;
  7 
  8 import javax.servlet.ServletOutputStream;
  9 import javax.servlet.http.HttpServletResponse;
 10 
 11 import net.sf.jasperreports.engine.JRDataSource;
 12 import net.sf.jasperreports.engine.JRExporterParameter;
 13 import net.sf.jasperreports.engine.JasperFillManager;
 14 import net.sf.jasperreports.engine.JasperPrint;
 15 import net.sf.jasperreports.engine.JasperReport;
 16 import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
 17 import net.sf.jasperreports.engine.export.JRPdfExporter;
 18 import net.sf.jasperreports.engine.util.JRLoader;
 19 
 20 import org.apache.poi.hssf.usermodel.HSSFCell;
 21 import org.apache.poi.hssf.usermodel.HSSFRow;
 22 import org.apache.poi.hssf.usermodel.HSSFSheet;
 23 import org.apache.poi.hssf.usermodel.HSSFWorkbook;
 24 import org.apache.struts2.ServletActionContext;
 25 
 26 import com.hrmsys.bean.EmployeeBean;
 27 
 28 public class FileExport {
 29     /**
 30      * pdf导出
 31      * 
 32      * @param list
 33      *            数据集合
 34      * @param filename
 35      *            导出的文件名称
 36      * @param response
 37      *            HttpServletResponse
 38      * @return
 39      */
 40     public void exportPDF(List list, String filename, String jaspername,
 41             HttpServletResponse response) {
 42         ServletOutputStream sos = null;
 43         try {
 44             String path = ServletActionContext.getServletContext().getRealPath(
 45                     "").replace("\\", "/");
 46             File file = new File(path + "/jasperreport/" + jaspername);
 47             //数据源就构造完毕
 48             JRDataSource dataSource = new JRBeanCollectionDataSource(list);
 49             //加载jasper
 50             JasperReport report = (JasperReport) JRLoader.loadObject(file
 51                     .getPath());
 52             //将数据和xml组合,生成需要的打印文件
 53             JasperPrint print = JasperFillManager.fillReport(report, null,
 54                     dataSource);
 55             ////生成我们的导出类JRPdfExporter 来自JRExporter  
 56             JRPdfExporter exporter = new JRPdfExporter();
 57             response.setContentType("application/pdf");
 58             response.setHeader("Content-Disposition", "attachment;filename="
 59                     + new String(filename.getBytes(), "ISO8859-1"));//转为此不会中文乱码
 60             sos = response.getOutputStream();
 61             ///设JasperPrint参数  
 62             exporter.setParameter(JRExporterParameter.JASPER_PRINT, print);
 63             //设置输入的PDF文件放在什么地方  
 64             exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, sos);
 65             //            //输出  
 66             exporter.exportReport();
 67         } catch (Exception e) {
 68             e.printStackTrace();
 69         } finally {
 70             if (sos != null) {
 71                 try {
 72                     sos.close();
 73                 } catch (IOException e) {
 74                     e.printStackTrace();
 75                 }
 76             }
 77         }
 78     }
 79 
 80 //    /**
 81 //     * 把字符串转成utf8编码,保证中文文件名不会乱码
 82 //     * new String(filename.getByte("UTF-8"),"UTF-8");不行
 83 //     * @param s
 84 //     * @return foxmail
 85 //     */
 86 //    public static String toUtf8String(String s) {
 87 //        StringBuffer sb = new StringBuffer();
 88 //        for (int i = 0; i < s.length(); i++) {
 89 //            char c = s.charAt(i);
 90 //            if (c >= 0 && c <= 255) {
 91 //                sb.append(c);
 92 //            } else {
 93 //                byte[] b;
 94 //                try {
 95 //                    b = Character.toString(c).getBytes("utf-8");
 96 //                } catch (Exception ex) {
 97 //                    System.out.println(ex);
 98 //                    b = new byte[0];
 99 //                }
100 //                for (int j = 0; j < b.length; j++) {
101 //                    int k = b[j];
102 //                    if (k < 0)
103 //                        k += 256;
104 //                    sb.append("%" + Integer.toHexString(k).toUpperCase());
105 //                }
106 //            }
107 //        }
108 //        return sb.toString();
109 //    }
110     /**
111      * jasperReport导出Excel 此方式导出的excel没有网格线(好像直接用流导出方式都没有)
112      * 在此直接用poi导出,当然jasperReport导出中也应用了poi(需要加入poi的jar包)
113      */
114     public void exportXls(List<EmployeeBean> list, String filename, HttpServletResponse response) {
115         //创建一工作空间
116         HSSFWorkbook workbook = new HSSFWorkbook();
117         //创建一表单
118         HSSFSheet sheet = workbook.createSheet(filename);
119         //创建表题行
120         HSSFRow headerRow = sheet.createRow(0);
121         for(int i = 0; i < 20; i++){
122             HSSFCell headerCell  = headerRow.createCell(i);
123             switch(i){
124             case 0 :
125                 headerCell.setCellValue("员工工号"); break;
126             case 1 :
127                 headerCell.setCellValue("员工姓名"); break;
128             case 2 :
129                 headerCell.setCellValue("性别"); break;
130             case 3 :
131                 headerCell.setCellValue("出生日期"); break;
132             case 4 :
133                 headerCell.setCellValue("地址"); break;
134             case 5:
135                 headerCell.setCellValue("邮编"); break;
136             case 6 :
137                 headerCell.setCellValue("电话"); break;
138             case 7 :
139                 headerCell.setCellValue("手机"); break;
140             case 8 :
141                 headerCell.setCellValue("QQ"); break;
142             case 9 :
143                 headerCell.setCellValue("email"); break;
144             case 10 :
145                 headerCell.setCellValue("银行账号"); break;
146             case 11 :
147                 headerCell.setCellValue("身份证号"); break;
148             case 12 :
149                 headerCell.setCellValue("部门"); break;
150             case 13 :
151                 headerCell.setCellValue("职位"); break;
152             case 14 :
153                 headerCell.setCellValue("国籍"); break;
154             case 15 :
155                 headerCell.setCellValue("籍贯"); break;
156             case 16 :
157                 headerCell.setCellValue("民族"); break;
158             case 17 :
159                 headerCell.setCellValue("毕业学校"); break;
160             case 18 :
161                 headerCell.setCellValue("学历"); break;
162             case 19 :
163                 headerCell.setCellValue("专业"); break;
164             }
165             }
166             for(int i = 0; i < list.size(); i++){
167                 HSSFRow row = sheet.createRow(i+1);
168                 EmployeeBean empBean = list.get(i);
169                 HSSFCell empIdCell = row.createCell(0);
170                 empIdCell.setCellValue(empBean.getEmpId());
171                 HSSFCell empNameCell = row.createCell(1);
172                 empNameCell.setCellValue(empBean.getEmpName());
173                 HSSFCell empSexCell = row.createCell(2);
174                 empSexCell.setCellValue(empBean.getEmpSex());
175                 HSSFCell empBirthCell = row.createCell(3);
176                 empBirthCell.setCellValue(empBean.getEmpBirth());
177                 HSSFCell empAddressCell = row.createCell(4);
178                 empAddressCell.setCellValue(empBean.getEmpAddress());
179                 HSSFCell empPostCell = row.createCell(5);
180                 empPostCell.setCellValue(empBean.getEmpPost());
181                 HSSFCell empTelephoneCell = row.createCell(6);
182                 empTelephoneCell.setCellValue(empBean.getEmpTelephone());
183                 HSSFCell empMobilephoneCell = row.createCell(7);
184                 empMobilephoneCell.setCellValue(empBean.getEmpMobilephone());
185                 HSSFCell empQqphoneCell = row.createCell(8);
186                 empQqphoneCell.setCellValue(empBean.getEmpQq());
187                 HSSFCell empEmailCell = row.createCell(9);
188                 empEmailCell.setCellValue(empBean.getEmpEmail());
189                 HSSFCell empAccountCell = row.createCell(10);
190                 empAccountCell.setCellValue(empBean.getEmpAccount());
191                 HSSFCell empIdcardCell = row.createCell(11);
192                 empIdcardCell.setCellValue(empBean.getEmpIdcard());
193                 HSSFCell deptCell = row.createCell(12);
194                 deptCell.setCellValue(empBean.getDept());
195                 HSSFCell jobCell = row.createCell(13);
196                 jobCell.setCellValue(empBean.getJob());
197                 HSSFCell empNationalityCell = row.createCell(14);
198                 empNationalityCell.setCellValue(empBean.getEmpNationality());
199                 HSSFCell empOriginCell = row.createCell(15);
200                 empOriginCell.setCellValue(empBean.getEmpOrigin());
201                 HSSFCell empNationCell = row.createCell(16);
202                 empNationCell.setCellValue(empBean.getEmpNation());
203                 HSSFCell empSchoolCell = row.createCell(17);
204                 empSchoolCell.setCellValue(empBean.getEmpSchool());
205                 HSSFCell empEducationCell = row.createCell(18);
206                 empEducationCell.setCellValue(empBean.getEmpEducation());
207                 HSSFCell empProfessionCell = row.createCell(19);
208                 empProfessionCell.setCellValue(empBean.getEmpProfession());
209             }
210             response.setContentType("application/xls");
211             ServletOutputStream sos = null;
212             try {
213                 response.setHeader("Content-Disposition", "attachment;filename="
214                         + new String(filename.getBytes(), "ISO8859-1"));
215                 sos = response.getOutputStream();
216                 workbook.write(sos);
217             } catch (Exception e) {
218                 e.printStackTrace();
219             }finally{
220                 if(sos != null){
221                     try {
222                         sos.close();
223                     } catch (IOException e) {
224                         e.printStackTrace();
225                     }
226                 }
227             }
228         }
229 }

 

posted on 2017-10-13 16:21  Sharpest  阅读(510)  评论(0编辑  收藏  举报