导出:将当前页面表格里值传到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类:

 package com.rjs.cloud.web.utils;

 import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.apache.commons.beanutils.PropertyUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook; public class ExportFile { public static void exportReport(HttpServletResponse response, List<? extends Object> list, String headerAsString,
String propertyAsString, String fileType, String titleName, Map<String, ? extends Object> mapResults) {
String excel = "xls";
if (excel.trim().equalsIgnoreCase(fileType)) {
response.setContentType("application/vnd.ms-xls");
try {
response.setHeader("Content-disposition",
"attachment; filename=" + new String(titleName.getBytes("gb2312"), "ISO8859-1") + ".xls");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} response.setHeader("Pragma", ""); OutputStream out = null;
try {
out = response.getOutputStream();
exportListToFile(out, list, headerAsString, propertyAsString, fileType, titleName, mapResults); out.close();
} catch (Exception e) {
e.printStackTrace();
}
} public static void exportReport(HttpServletResponse response, HttpServletRequest request,
List<? extends Object> list, String headerAsString, String propertyAsString, String fileType,
String titleName, Map<String, ? extends Object> mapResults, String fileName) {
String excel = "xls";
if (excel.trim().equalsIgnoreCase(fileType)) {
response.setContentType("application/vnd.ms-xls");
try {
String agent = request.getHeader("User-Agent");
boolean isMSIE = (agent != null && agent.indexOf("MSIE") != -1);
if (isMSIE) {// IE浏览器
fileName = URLEncoder.encode(fileName, "UTF-8");
} else {// 其它浏览器
fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
}
response.setHeader("Content-disposition", "attachment; filename=" + fileName + ".xls");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} } response.setHeader("Pragma", ""); OutputStream out = null;
try {
out = response.getOutputStream();
exportListToFile(out, list, headerAsString, propertyAsString, fileType, titleName, mapResults); out.close();
} catch (Exception e) {
e.printStackTrace();
}
} public static void exportListToFile(OutputStream out, List<? extends Object> list, String headerAsString,
String propertyAsString, String fileType, String titleName, Map<String, ? extends Object> mapResults) {
String[] header = headerAsString.split(",");
String[] property = propertyAsString.split(",");
ExportColumnInfo[] columnInfo = new ExportColumnInfo[header.length + 1];
String sNo = "S/No";
columnInfo[0] = new ExportColumnInfo(sNo, "", 10);
for (int i = 1; i < header.length + 1; i++) {
columnInfo[i] = new ExportColumnInfo(header[i - 1], property[i - 1], 10);
}
String excel = "XLS";
if (list != null && list.size() > 0) {
try {
doExport(out, titleName, columnInfo, list);
} catch (Exception e) {
e.printStackTrace();
}
} } public static void doExport(OutputStream out, String title, ExportColumnInfo[] columnInfo,
List<? extends Object> values) throws Exception {
int rows = values.size();
int columns = columnInfo.length;
String[][] cells = new String[rows][columns];
for (int i = 0; i < rows; i++) {
Object curr = values.get(i);
for (int j = 0; j < columns; j++) {
if (j == 0) {
cells[i][0] = String.valueOf(i + 1);
} else {
Object val = PropertyUtils.getProperty(curr, columnInfo[j].getProperty());
cells[i][j] = val == null ? "" : "" + val;
}
}
}
doExport(out, title, columnInfo, cells); } public static void doExport(OutputStream out, String title, ExportColumnInfo[] columnInfo, String[][] cellValues)
throws Exception {
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet(title); // add head message
int rowIndex = 0; // row1 filled in all title
HSSFRow row = sheet.createRow(rowIndex);
rowIndex++;
HSSFFont f_title = wb.createFont();
f_title.setFontHeightInPoints((short) 11);
f_title.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
f_title.setFontName("Arial"); HSSFCellStyle style = wb.createCellStyle();
style.setFont(f_title);
style.setAlignment(HSSFCellStyle.ALIGN_CENTER); for (int i = 0; i < columnInfo.length; i++) {
sheet.setColumnWidth(Short.valueOf(String.valueOf(i)),
Short.valueOf(String.valueOf(columnInfo[i].getWidth() * 256)));
HSSFCell cell = row.createCell(Short.valueOf(String.valueOf(i)));
cell.setCellStyle(style);
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
cell.setCellValue(new HSSFRichTextString(columnInfo[i].getLabel()));
}
HSSFCellStyle style2 = wb.createCellStyle(); for (int i = 0; i < cellValues.length; i++) {
HSSFRow row1 = sheet.createRow(rowIndex + i);
for (int j = 0; j < cellValues[i].length; j++) {
HSSFCell cell = row1.createCell(Short.valueOf(String.valueOf(j)));
style2.setAlignment(HSSFCellStyle.ALIGN_RIGHT);
cell.setCellStyle(style2);
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
cell.setCellValue(new HSSFRichTextString(cellValues[i][j])); }
} wb.write(out);
out.close();
} }

SSM框架下实现导出功能的更多相关文章

  1. SSM框架下实现导入功能

    何叫导入?简单说,导入就是把excel表格里的数据插入到数据库里.我这里做的是支持.xls和.xlsx格式. 因为是自己做案例记录,那些jar包什么的就不细说了,主要讲实现和步骤,看代码: 先在你的项 ...

  2. 关于在SSM框架下使用PageHelper

    首先,如果各位在这块配置和代码有什么问题欢迎说出来,我也会尽自己最大的能力帮大家解答 这些代码我都是写在一个小项目里的,项目的github地址为:https://github.com/Albert-B ...

  3. ssm框架下怎么批量删除数据?

    ssm框架下批量删除怎么删除? 1.单击删除按钮选中选项后,跳转到js函数,由函数处理 2. 主要就是前端的操作 js 操作(如何全选?如何把选中的数据传到Controller中) 3.fun()函数 ...

  4. SSM框架的整合思路&功能实现

    这是我第一篇博客,关于SSM框架的整合思路以及简单功能实现. 首先,最近刚刚学习Spring+SpringMVC+Mybatis,在开发时遇到形形色色的问题,周遭人也为我提供了一些思路,我会一点点整理 ...

  5. Jquery DataTable AJAX跨域请求的解决方法及SSM框架下服务器端返回JSON格式数据的解决方法

    如题,用HBuilder开发APP,涉及到用AJAX跨域请求后台数据,刚接触,费了不少时间.幸得高手指点,得以解决. APP需要用TABLE来显示数据,因此采用了JQ 的DataTable.  在实现 ...

  6. SSM框架下分页的实现(封装page.java和List<?>)

    之前写过一篇博客  java分页的实现(后台工具类和前台jsp页面),介绍了分页的原理. 今天整合了Spring和SpringMVC和MyBatis,做了增删改查和分页,之前的逻辑都写在了Servle ...

  7. ssm框架下实现文件上传

      1.由于ssm框架是使用Maven进行管理的,文件上传所需要的jar包利用pom.xml进行添加,如下所示: <properties> <commons-fileupload.v ...

  8. SSM框架下 Failed to load resource: the server responded with a status of 404 (Not Found)错误

    这个错误提示的是js的引用路径有错: 1.检查应用路径是否正确(我的问题是路径是正确的但是去到页面就会提示404错误) 引用路径,最好都使用绝对路径 <script type="tex ...

  9. SSM框架下的redis缓存

    基本SSM框架搭建:http://www.cnblogs.com/fuchuanzhipan1209/p/6274358.html 配置文件部分: 第一步:加入jar包 pom.xml <!-- ...

随机推荐

  1. es6 import 与 export

    1.export 命令 export 命令用于规定模块的对外接口. 一个模块就是一个独立的文件.该文件内部所有的变量,外部无法获取.要想外部能够读取模块内部的某个变量,就必须使用 export 关键字 ...

  2. SpringCloud服务组合

    SpringCloud生态强调微服务,微服务也就意味着将各个功能独立的业务抽象出来,做成一个单独的服务供外部调用.但每个人对服务究竟要有多“微”的理解差异很大,导致微服务的粒度很难掌控,划分规则也不统 ...

  3. 根据JSON创建对应的HIVE表

    本文提供一种用SCALA把JSON串转换为HIVE表的方法,由于比较简单,只贴代码,不做解释.有问题可以留言探讨 package com.gabry.hiveimport org.json4s._im ...

  4. 洛谷2019 3月月赛 T3

    题干 唯一AC T3 的大巨佬%%% 这题就是个大模拟吧. 题解

  5. 【转】mysql的数据类型

    转自:http://mrxiong.blog.51cto.com/287318/1651098 一.数值类型 Mysql支持所有标准SQL中的数值类型,其中包括严格数据类型(INTEGER,SMALL ...

  6. MVC系列学习(十)-生成URL与表单

    本次学习,在路由配置信息中,有两个路由规则,在网站第一次启动的时候,注册了两个路由表 1.动态生成url A.在路由规则中,因为Default在前面,所以最新找到该路由表,此时不管 自己定义的控制器名 ...

  7. jdk11安装没有jre文件夹

    原因:jdk11安装之后是没有jre的 如果需要jre,需要到jdk目录下面去    打开命令窗口,然后执行如下命令:    bin\jlink.exe --module-path jmods --a ...

  8. Jquery 可拖拽的Ztree

    比较懒,就只贴关键代码吧,自己把有用的属性全部打印出来了,也加了不少注释. 保存后涉及到的排序问题,刷新问题还未考虑到,后面有的话再加. $.fn.zTree.init($("#ztree& ...

  9. B树、B+树、红黑树、AVL树比较

    B树是为了提高磁盘或外部存储设备查找效率而产生的一种多路平衡查找树. B+树为B树的变形结构,用于大多数数据库或文件系统的存储而设计. B树相对于红黑树的区别 在大规模数据存储的时候,红黑树往往出现由 ...

  10. [ ZJOI 2006 ] Mahjong

    \(\\\) \(Description\) 现有权值分别为\(1\text~100\)的\(100\)种牌,分别给出每种排的张数\(A_i\),试判断能否胡牌,胡牌需要将所有牌不重不漏地分成以下几类 ...