导出:将当前页面表格里值传到excel表格中。
一、页面js
//下载excel
$("#download").click(
function() {
var param = $("#form_enterpriseUser").serialize(); //序列化整个表单的值,在ajax里用
var url = "${pageContext.request.contextPath}/enterpriseUser/EnterpriseUserDownLoad?"+ param;
window.location.href = url;
})
二、Controller类:
/**
* 下载excel表格
* @param page
* @param size
* @param userAccount
* @param userName
* @param groupId
* @param instructionOpt
* @param powercutOpt
* @param smsAlarmOpt
* @param smsLoginOpt
* @param roleId
* @param corpId
*/
@RequestMapping(value = "/EnterpriseUserDownLoad" , method = RequestMethod.GET)
public void EnterpriseUserDownLoad (
@RequestParam(required = false) String userAccount,
@RequestParam(required = false) String userName,
@RequestParam(required = false) String groupId,
@RequestParam(required = false) String instructionOpt,
@RequestParam(required = false) String powercutOpt,
@RequestParam(required = false) String smsAlarmOpt,
@RequestParam(required = false) String smsLoginOpt,
@RequestParam(required = false) String roleId,
@RequestParam(required = false) String corpId,
HttpServletResponse response,
HttpServletRequest request) {
final List<CorpUserDTO> resp = corpUserService.queryCorpUsersExl( new CorpUserReq(corpId,userAccount,
userName,groupId,0,0,instructionOpt,powercutOpt,smsAlarmOpt,smsLoginOpt,roleId));
String headerAsString = "用户ID,用户账号,用户姓名,手机号码,角色,职位名称,无线设备设置权限,断油断电设置权限,短信报警权限,信息保密,企业名称,状态";
String propertyAsString = "id,userAccount,userName,telephone,roleValue,job,instructionOpt,powercutOpt,smsAlarmOpt,smsLoginOpt,corpName,statusValue";
ExportFile.exportReport(response, request, resp, headerAsString, propertyAsString, "xls", "to export excel",
null, "下载excel");
}
三、Service类:
List<CorpUserDTO> queryCorpUsersExl(CorpUserReq corpUserReq); //CorpUserReq对DTO实体进行封装
四、实现类:
@Override
public List<CorpUserDTO> queryCorpUsersExl(CorpUserReq corpUserReq) {
try {
Preconditions.checkNotNull(corpUserReq);
final RowBounds rowBounds = new RowBounds();
final List<CorpUserDTO> corpUserList = corpUserDAO.queryCorpUsers(corpUserReq, rowBounds);
return corpUserList;
} catch (final Exception e) {
logger.error("queryCorpUsers:" + e);
throw new ServiceException("查询用户失败");
}
}
五、DAO层
List<CorpUserDTO> queryCorpUsers(CorpUserReq corpUserReq, RowBounds rowBounds);
六、SQL
<select id="queryCorpUsers" resultMap="CorpUserDTOMap"
parameterType="com.rjs.gps.api.dto.corp.user.CorpUserReq">
select cop.* from (
select
<include refid="CorpUserDTOMap" />
,if(cu.status = '0','正常','已停用') as statusValue, gc.corp_name,
(select GROUP_CONCAT(cr.role_name) from gps_corp_user_role_rel_${corpId} cur
left join gps_corp_role_${corpId} cr on cur.corp_id = cr.corp_id and cur.role_id =cr.id
where cu.corp_id = cur.corp_id and
cu.id
= cur.user_id
) as role_value,cg.group_name,
(select if(count(1)<![CDATA[>]]>0 ,1,0) from gps_corp_user_role_rel_${corpId} cur
left join gps_corp_role_${corpId} cr on cur.corp_id =
cr.corp_id and cur.role_id =
cr.id
where cu.corp_id = cur.corp_id and
cu.id
= cur.user_id and cr.is_admin=1
) as is_admin
from gps_corp_user_${corpId} cu
left join gps_corp_group_${corpId} cg on
cu.corp_id = cg.corp_id and cu.group_id =
cg.id
left join gps_corp gc
on gc.id = cu.corp_id
where cu.corp_id =
#{corpId,jdbcType=VARCHAR} and cu.status <![CDATA[<>]]> 2 and cu.channel= 0
<if test="userAccount != null and userAccount != ''">
and cu.user_account like
concat('%',#{userAccount,jdbcType=VARCHAR},'%')
</if>
<if test="userName != null and userName != ''">
and cu.user_name like
concat('%',#{userName,jdbcType=VARCHAR},'%')
</if>
<if test="groupId != null and groupId != ''">
and cu.group_id = #{groupId,jdbcType=VARCHAR}
</if>
<if test="instructionOpt != null and instructionOpt != ''">
and cu.instruction_opt = #{instructionOpt,jdbcType=VARCHAR}
</if>
<if test="powercutOpt != null and powercutOpt != ''">
and cu.powercut_opt = #{powercutOpt,jdbcType=VARCHAR}
</if>
<if test="smsAlarmOpt != null and smsAlarmOpt != ''">
and cu.sms_alarm_opt = #{smsAlarmOpt,jdbcType=VARCHAR}
</if>
<if test="smsLoginOpt != null and smsLoginOpt != ''">
and cu.sms_login_opt = #{smsLoginOpt,jdbcType=VARCHAR}
</if>
) cop
where 1=1
<if test="roleId !=null and roleId !=''">
and cop.role_value=(select role_name from gps_corp_role_${corpId} table2 where table2.id=#{roleId,jdbcType=VARCHAR})
</if>
order by cop.create_time desc
</select>
<include refid="CorpUserDTOMap" /> 字段写在下方:
<sql id="CorpUserDTOMap">
cu.id, cu.corp_id, cu.dept_id, cu.group_id,
cu.user_account, cu.user_name,
cu.password,cu.salt,cu.is_first_login,
(select GROUP_CONCAT(cucr.car_id) from gps_corp_user_car_ref_${corpId} cucr where cucr.user_id = cu.id) as user_level,
cu.telephone,cu.job,
cu.equip_auth,cu.status,cu.last_mod_time,cu.create_time,cu.wifi_auth_pwd,cu.error_day,cu.error_times,cu.last_alert_time,cu.is_alert_timing,
cu.coordinate,cu.instruction_opt,cu.powercut_opt,cu.sms_alarm_opt,cu.sms_login_opt,cu.channel,cu.stop_normal_val,cu.offline_normal_val,cu.secret_opt
</sql>
CorpUserReq 封装层:
public class CorpUserReq extends BaseReq {
private static final long serialVersionUID = -5378994308037645116L;
private String corpId;
private String userId;
private String userAccount;
private String userName;
private String groupId;
private String instructionOpt;
private String powercutOpt;
private String smsAlarmOpt;
private String smsLoginOpt;
private String roleId;
public CorpUserReq(String corpId, String userId, int page, int size) {
super(page, size);
this.corpId = corpId;
this.userId = userId;
}
public CorpUserReq(String corpId, String userAccount, String userName, String groupId, int page, int size) {
super(page, size);
this.corpId = corpId;
this.userAccount = userAccount;
this.userName = userName;
this.groupId = groupId;
}
public CorpUserReq(String corpId, String userAccount, String userName, String groupId, int page, int size,
String instructionOpt, String powercutOpt, String smsAlarmOpt, String smsLoginOpt, String roleId) {
super(page, size);
this.corpId = corpId;
this.userAccount = userAccount;
this.userName = userName;
this.groupId = groupId;
this.instructionOpt = instructionOpt;
this.powercutOpt = powercutOpt;
this.smsAlarmOpt = smsAlarmOpt;
this.smsLoginOpt = smsLoginOpt;
this.roleId = roleId;
}
public String getCorpId() {
return corpId;
}
public String getGroupId() {
return groupId;
}
public String getInstructionOpt() {
return instructionOpt;
}
public String getPowercutOpt() {
return powercutOpt;
}
public String getRoleId() {
return roleId;
}
public String getSmsAlarmOpt() {
return smsAlarmOpt;
}
public String getSmsLoginOpt() {
return smsLoginOpt;
}
public String getUserAccount() {
return userAccount;
}
public String getUserId() {
return userId;
}
public String getUserName() {
return userName;
}
public void setCorpId(String corpId) {
this.corpId = corpId;
}
public void setGroupId(String groupId) {
this.groupId = groupId;
}
public void setInstructionOpt(String instructionOpt) {
this.instructionOpt = instructionOpt;
}
public void setPowercutOpt(String powercutOpt) {
this.powercutOpt = powercutOpt;
}
public void setRoleId(String roleId) {
this.roleId = roleId;
}
public void setSmsAlarmOpt(String smsAlarmOpt) {
this.smsAlarmOpt = smsAlarmOpt;
}
public void setSmsLoginOpt(String smsLoginOpt) {
this.smsLoginOpt = smsLoginOpt;
}
public void setUserAccount(String userAccount) {
this.userAccount = userAccount;
}
public void setUserId(String userId) {
this.userId = userId;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
ExportFile类:
1 package com.rjs.cloud.web.utils; 2 3 import java.io.OutputStream; 4 import java.io.UnsupportedEncodingException; 5 import java.net.URLEncoder; 6 import java.util.List; 7 import java.util.Map; 8 9 import javax.servlet.http.HttpServletRequest; 10 import javax.servlet.http.HttpServletResponse; 11 12 import org.apache.commons.beanutils.PropertyUtils; 13 import org.apache.poi.hssf.usermodel.HSSFCell; 14 import org.apache.poi.hssf.usermodel.HSSFCellStyle; 15 import org.apache.poi.hssf.usermodel.HSSFFont; 16 import org.apache.poi.hssf.usermodel.HSSFRichTextString; 17 import org.apache.poi.hssf.usermodel.HSSFRow; 18 import org.apache.poi.hssf.usermodel.HSSFSheet; 19 import org.apache.poi.hssf.usermodel.HSSFWorkbook; 20 21 public class ExportFile { 22 23 public static void exportReport(HttpServletResponse response, List<? extends Object> list, String headerAsString, 24 String propertyAsString, String fileType, String titleName, Map<String, ? extends Object> mapResults) { 25 String excel = "xls"; 26 if (excel.trim().equalsIgnoreCase(fileType)) { 27 response.setContentType("application/vnd.ms-xls"); 28 try { 29 response.setHeader("Content-disposition", 30 "attachment; filename=" + new String(titleName.getBytes("gb2312"), "ISO8859-1") + ".xls"); 31 } catch (UnsupportedEncodingException e) { 32 e.printStackTrace(); 33 } 34 } 35 36 response.setHeader("Pragma", ""); 37 38 OutputStream out = null; 39 try { 40 out = response.getOutputStream(); 41 exportListToFile(out, list, headerAsString, propertyAsString, fileType, titleName, mapResults); 42 43 out.close(); 44 } catch (Exception e) { 45 e.printStackTrace(); 46 } 47 } 48 49 public static void exportReport(HttpServletResponse response, HttpServletRequest request, 50 List<? extends Object> list, String headerAsString, String propertyAsString, String fileType, 51 String titleName, Map<String, ? extends Object> mapResults, String fileName) { 52 String excel = "xls"; 53 if (excel.trim().equalsIgnoreCase(fileType)) { 54 response.setContentType("application/vnd.ms-xls"); 55 try { 56 String agent = request.getHeader("User-Agent"); 57 boolean isMSIE = (agent != null && agent.indexOf("MSIE") != -1); 58 if (isMSIE) {// IE浏览器 59 fileName = URLEncoder.encode(fileName, "UTF-8"); 60 } else {// 其它浏览器 61 fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1"); 62 } 63 response.setHeader("Content-disposition", "attachment; filename=" + fileName + ".xls"); 64 } catch (UnsupportedEncodingException e) { 65 e.printStackTrace(); 66 } 67 68 } 69 70 response.setHeader("Pragma", ""); 71 72 OutputStream out = null; 73 try { 74 out = response.getOutputStream(); 75 exportListToFile(out, list, headerAsString, propertyAsString, fileType, titleName, mapResults); 76 77 out.close(); 78 } catch (Exception e) { 79 e.printStackTrace(); 80 } 81 } 82 83 public static void exportListToFile(OutputStream out, List<? extends Object> list, String headerAsString, 84 String propertyAsString, String fileType, String titleName, Map<String, ? extends Object> mapResults) { 85 String[] header = headerAsString.split(","); 86 String[] property = propertyAsString.split(","); 87 ExportColumnInfo[] columnInfo = new ExportColumnInfo[header.length + 1]; 88 String sNo = "S/No"; 89 columnInfo[0] = new ExportColumnInfo(sNo, "", 10); 90 for (int i = 1; i < header.length + 1; i++) { 91 columnInfo[i] = new ExportColumnInfo(header[i - 1], property[i - 1], 10); 92 } 93 String excel = "XLS"; 94 if (list != null && list.size() > 0) { 95 try { 96 doExport(out, titleName, columnInfo, list); 97 } catch (Exception e) { 98 e.printStackTrace(); 99 } 100 } 101 102 } 103 104 public static void doExport(OutputStream out, String title, ExportColumnInfo[] columnInfo, 105 List<? extends Object> values) throws Exception { 106 int rows = values.size(); 107 int columns = columnInfo.length; 108 String[][] cells = new String[rows][columns]; 109 for (int i = 0; i < rows; i++) { 110 Object curr = values.get(i); 111 for (int j = 0; j < columns; j++) { 112 if (j == 0) { 113 cells[i][0] = String.valueOf(i + 1); 114 } else { 115 Object val = PropertyUtils.getProperty(curr, columnInfo[j].getProperty()); 116 cells[i][j] = val == null ? "" : "" + val; 117 } 118 } 119 } 120 doExport(out, title, columnInfo, cells); 121 122 } 123 124 public static void doExport(OutputStream out, String title, ExportColumnInfo[] columnInfo, String[][] cellValues) 125 throws Exception { 126 HSSFWorkbook wb = new HSSFWorkbook(); 127 HSSFSheet sheet = wb.createSheet(title); 128 129 // add head message 130 int rowIndex = 0; 131 132 // row1 filled in all title 133 HSSFRow row = sheet.createRow(rowIndex); 134 rowIndex++; 135 HSSFFont f_title = wb.createFont(); 136 f_title.setFontHeightInPoints((short) 11); 137 f_title.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); 138 f_title.setFontName("Arial"); 139 140 HSSFCellStyle style = wb.createCellStyle(); 141 style.setFont(f_title); 142 style.setAlignment(HSSFCellStyle.ALIGN_CENTER); 143 144 for (int i = 0; i < columnInfo.length; i++) { 145 sheet.setColumnWidth(Short.valueOf(String.valueOf(i)), 146 Short.valueOf(String.valueOf(columnInfo[i].getWidth() * 256))); 147 HSSFCell cell = row.createCell(Short.valueOf(String.valueOf(i))); 148 cell.setCellStyle(style); 149 cell.setCellType(HSSFCell.CELL_TYPE_STRING); 150 cell.setCellValue(new HSSFRichTextString(columnInfo[i].getLabel())); 151 } 152 HSSFCellStyle style2 = wb.createCellStyle(); 153 154 for (int i = 0; i < cellValues.length; i++) { 155 HSSFRow row1 = sheet.createRow(rowIndex + i); 156 for (int j = 0; j < cellValues[i].length; j++) { 157 HSSFCell cell = row1.createCell(Short.valueOf(String.valueOf(j))); 158 style2.setAlignment(HSSFCellStyle.ALIGN_RIGHT); 159 cell.setCellStyle(style2); 160 cell.setCellType(HSSFCell.CELL_TYPE_STRING); 161 cell.setCellValue(new HSSFRichTextString(cellValues[i][j])); 162 163 } 164 } 165 166 wb.write(out); 167 out.close(); 168 } 169 170 }