Sfoglia il codice sorgente

健康小屋-excel 导出demo

huangzhiyong 6 anni fa
parent
commit
961c922a48

+ 6 - 1
svr/svr-healthy-house/pom.xml

@ -147,7 +147,12 @@
			<artifactId>poi-ooxml-schemas</artifactId>
		</dependency>
		<!--   poi xml导入导出工具 end -->
		<!--jxl导出工具-->
		<dependency>
			<groupId>net.sourceforge.jexcelapi</groupId>
			<artifactId>jxl</artifactId>
			<version>2.6.10</version>
		</dependency>
	</dependencies>
	<build>

+ 140 - 0
svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/controller/user/UserController.java

@ -13,11 +13,21 @@ import com.yihu.jw.restmodel.wlyy.HouseUserContant;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import jxl.write.Colour;
import jxl.write.WritableCellFormat;
import org.apache.log4j.spi.ErrorCode;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
@ -131,6 +141,136 @@ public class UserController  extends EnvelopRestEndpoint {
        }
    }
    /******************************   导入导出   ***********************************/
    @RequestMapping("/exportToExcel")
    public void exportToExcel(
            HttpServletResponse response,
            @ApiParam(name = "city", value = "所在市区", required = false)@RequestParam(required = false, name = "city") String city,
            @ApiParam(name = "activated", value = "用户状态", required = false)@RequestParam(required = false, name = "activated") String activated ,
            @ApiParam(name = "name", value = "姓名/手机号", required = false)@RequestParam(required = false, name = "name") String name ,
            @ApiParam(name = "sort", value = "使用次数排序", required = false)@RequestParam(required = false, name = "sort") String sort) throws ManageException {
        Envelop envelop = new Envelop();
        //获取用户数据
        Map<String, String> map = new HashMap<>();
        map.put("cityCode",city);
        map.put("activated",activated);
        map.put("name",name);
        map.put("telephone",name);
        List<User> userList = userService.userList( map, sort);
        try {
            String fileName = "标准数据集"+"_";
            //设置下载
            response.setContentType("octets/stream");
            response.setHeader("Content-Disposition", "attachment; filename="
                    + new String( fileName.getBytes("gb2312"), "ISO8859-1" )+".xlsx");
            OutputStream os = response.getOutputStream();
            //获取导出数据集
            JSONObject order = new JSONObject();
            order.put("id","asc");
            //获取导出数据元
            String ids="";
            User userInfo;
            for(int i=0;i<userList.size();i++){
                userInfo =   userList.get(i);
                if(i!=0){
                    ids+=",";
                }
                ids +=userInfo.getId();
            }
            //写excel
            Workbook workbook = new XSSFWorkbook();
            int k=0;
            User metaData = null;
            int row=0;
                //创建Excel工作表 指定名称和位置
                String streetName = "健康小屋-用户列表";
                Sheet sheet = workbook.createSheet(streetName);
                addStaticCell(sheet);
                addCell(sheet,1,0,"测试行");//名称
                //添加数据元信息
                WritableCellFormat wc = new WritableCellFormat();
                wc.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN, Colour.SKY_BLUE);//边框
                for(int j=0;k<userList.size(); j++,k++){
                    metaData = userList.get(k);
                    row=j+2;
                    addCell(sheet,0,row,j+1+"");//序号
                    addCell(sheet,1,row, metaData.getId());//内部id
                    addCell(sheet,2,row, metaData.getLoginCode());//登录名
                    addCell(sheet,3,row, metaData.getName());//名称
                    addCell(sheet,4,row, metaData.getGender());//性别
                    addCell(sheet,5,row, metaData.getTelephone());//电话
                    addCell(sheet,6,row, metaData.getCityName() + metaData.getAreaName() + metaData.getStreet());//地区
                    addCell(sheet,7,row, metaData.getFacilityUsedCount().toString());//使用设施次数
                    addCell(sheet,8,row, metaData.getIdCardNo());//身份证
                }
            //写入工作表
            workbook.write(os);
            workbook.close();
            os.flush();
            os.close();
        } catch (Exception e) {
            Envelop.getError("导出用户列表失败!");
        }
    }
    //添加单元格内容
    private void addCell(Sheet sheet,int column,int row,String data){
        Row sheetRow = sheet.getRow(row);
        if(sheetRow==null){
            sheetRow = sheet.createRow(row);
        }
        Cell cell= sheetRow.createCell(column);
        cell.setCellValue(data);
    }
    //添加单元格内容带样式
    private void addCell(Sheet sheet,int column,int row,String data,CellStyle cellStyle){
        Row sheetRow = sheet.getRow(row);
        if(sheetRow==null){
            sheetRow = sheet.createRow(row);
        }
        Cell cell= sheetRow.createCell(column);
        cell.setCellValue(data);
        cell.setCellStyle(cellStyle);
    }
    //excel中添加固定内容
    private void addStaticCell(Sheet sheet){
        addCell(sheet,0,0,"名称");
        addCell(sheet,0,1,"标识");
        addCell(sheet,0,2,"参考");
        addCell(sheet,0,3,"备注");
        //设置样式
        Workbook workbook = sheet.getWorkbook();
        CellStyle style = workbook.createCellStyle();
        style.setFillForegroundColor(IndexedColors.LIGHT_BLUE.getIndex());//設置背景色
//        style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
//        style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 居中
        Font font = workbook.createFont();
        font.setFontName("黑体");
        font.setFontHeightInPoints((short) 12);
        style.setFont(font);
        addCell(sheet,0,4,"序号",style);
        addCell(sheet,1,4,"内部标识",style);
        addCell(sheet,2,4,"数据元编码",style);
        addCell(sheet,3,4,"数据元名称",style);
        addCell(sheet,4,4,"数据元定义",style);
        addCell(sheet,5,4,"数据类型",style);
        addCell(sheet,6,4,"表示形式",style);
        addCell(sheet,7,4,"术语范围值",style);
        addCell(sheet,8,4,"列名",style);
        addCell(sheet,9,4,"列类型",style);
        addCell(sheet,10,4,"列长度",style);
        addCell(sheet,11,4,"主键",style);
        addCell(sheet,12,4,"可为空",style);
    }

+ 40 - 0
svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/model/user/User.java

@ -44,6 +44,14 @@ public class User extends UuidIdentityEntityWithOperator {
    private String provinceCode;    //省编码
    @Column(name = "city_code", nullable = false)
    private String cityCode;        //市编码
    @Column(name = "city_name", nullable = false)
    private String cityName;        //市名称
    @Column(name = "area_code", nullable = false)
    private String areaCode;        //所在县区编码
    @Column(name = "area_name", nullable = false)
    private String areaName;        //所在县区名称
    @Column(name = "street", nullable = false)
    private String street;        //所在街道名称
    @Column(name = "salt")
    private String salt; //加密种子
@ -178,4 +186,36 @@ public class User extends UuidIdentityEntityWithOperator {
    public void setActivatedContent(String activatedContent) {
        this.activatedContent = activatedContent;
    }
    public String getCityName() {
        return cityName;
    }
    public void setCityName(String cityName) {
        this.cityName = cityName;
    }
    public String getAreaCode() {
        return areaCode;
    }
    public void setAreaCode(String areaCode) {
        this.areaCode = areaCode;
    }
    public String getAreaName() {
        return areaName;
    }
    public void setAreaName(String areaName) {
        this.areaName = areaName;
    }
    public String getStreet() {
        return street;
    }
    public void setStreet(String street) {
        this.street = street;
    }
}

+ 35 - 43
svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/service/user/LoginService.java

@ -38,10 +38,8 @@ public class LoginService {
    private WlyyRedisVerifyCodeService wlyyRedisVerifyCodeService;
    @Value("${jw.smsUrl}")
    private String smsUrl;
    /**
     * 手机验证码方式登录并自动注册
     *
     *  手机验证码方式登录并自动注册
     * @param loginCode
     * @return
     * @throws Exception
@ -57,7 +55,7 @@ public class LoginService {
            user.setName(loginCode);
            user.setTelephone(loginCode);
            user.setPassword(LoginInfo.DEFAULT_PASSWORD);
        } else {
        }else {
            //已注册用户更改用户状态
            user.setActivated(HouseUserContant.activated_active);
        }
@ -67,27 +65,26 @@ public class LoginService {
        request.getSession().setAttribute(LoginInfo.LOGIN_CODE, user.getLoginCode());
        request.getSession().setAttribute(LoginInfo.USER_ID, user.getId());
        user.setLastLoginTime(new Date());
        userService.saveOrUpdate(user, LoginInfo.SAVE_TYPE_PHONE);
        userService.saveOrUpdate(user,LoginInfo.SAVE_TYPE_PHONE);
        return user;
    }
    /**
     * i健康账户登录&注册
     *
     * @param loginCode
     * @param password
     * @return
     * @throws Exception
     */
    @Transactional(noRollbackForClassName = "ManageException")
    public User iJklogin(HttpServletRequest request, String clientId, String loginCode, String password) throws ManageException {
    public User iJklogin(HttpServletRequest request,String clientId, String loginCode, String password) throws ManageException {
        //判断登陆信息是否正确
        User user = userService.findByCode(loginCode);
        if (user == null) {
            //i健康登录认证
            Map<String, Object> data = oauthIjkLogin(clientId, loginCode, password);
            if (data != null) {
            Map<String, Object> data = oauthIjkLogin(clientId,loginCode, password);
            if (data!=null ) {
                user = new User();
                user.setPassword(password);
                user.setLoginCode((String) data.get("user"));
@ -96,7 +93,7 @@ public class LoginService {
                user.setIdCardNo((String) data.get("idcard"));
                user.setTelephone((String) data.get("mobile"));
            } else {
            }else {
                String message = "账号不存在";
                throw new ManageException(message);
            }
@ -111,20 +108,19 @@ public class LoginService {
        request.getSession().setAttribute(LoginInfo.USER_ID, user.getId());
        user.setActivated(HouseUserContant.activated_active);
        user.setLastLoginTime(new Date());
        userService.saveOrUpdate(user, LoginInfo.SAVE_TYPE_IJK);
        userService.saveOrUpdate(user,LoginInfo.SAVE_TYPE_IJK);
        return user;
    }
    /**
     * i健康用户信息认证
     *
     *  i健康用户信息认证
     * @param username
     * @param password
     * @return
     * @throws ManageException
     */
    public Map<String, Object> oauthIjkLogin(String clientId, String username, String password) throws ManageException {
    public Map<String, Object> oauthIjkLogin(String clientId,String username, String password) throws ManageException{
        HashMap<String, Object> userDetail = null;
        HttpHeaders reqHeaders = new HttpHeaders();
        reqHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
@ -135,18 +131,17 @@ public class LoginService {
        params.add("login_type", "1");
        HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<>(params, reqHeaders);
        HashMap<String, Object> result = restTemplate.postForObject("http://svr-authentication:10260/oauth/login", httpEntity, HashMap.class);
        if (200 == (Integer) result.get("status")) {
            userDetail = (HashMap) result.get("obj");
            return userDetail;
        } else {
        if (200 == (Integer) result.get("status")){
            userDetail =  (HashMap)result.get("obj");
        return userDetail;
        }else {
            throw new ManageException("i健康用户认证失败");
        }
    }
    /**
     * 登出
     *
     *  登出
     * @param loginCode
     * @param password
     * @return
@ -171,20 +166,19 @@ public class LoginService {
        request.getSession().removeAttribute(LoginInfo.LOGIN_NAME);
        request.getSession().removeAttribute(LoginInfo.USER_ID);
        user.setActivated(HouseUserContant.activated_offline);
        userService.saveOrUpdate(user, "systemLogin");
        userService.saveOrUpdate(user,"systemLogin");
        return user;
    }
    /**
     * 发送短信
     *
     * @param clientId 应用id
     * @param type     短信类型
     * @param phone    接收手机号码
     *  发送短信
     * @param clientId     应用id
     * @param type          短信类型
     * @param phone         接收手机号码
     * @return
     */
    public ResponseEntity<HashMap> sendSms(String clientId, String type, String phone) throws ParseException, ManageException {
    public  ResponseEntity<HashMap> sendSms(String clientId, String type, String phone) throws ParseException, ManageException {
        //发送短信获取验证码
        HttpHeaders reqHeaders = new HttpHeaders();
        reqHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
@ -194,8 +188,8 @@ public class LoginService {
        params.add("to", phone);
        HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<>(params, reqHeaders);
        HashMap<String, Object> result = restTemplate.postForObject(smsUrl, httpEntity, HashMap.class);
        if (200 == (Integer) result.get("status")) {
            Map<String, Object> sms = (Map) result.get("obj");
        if (200 == (Integer) result.get("status")){
            Map<String, Object> sms =  (Map)result.get("obj");
            String captcha = (String) sms.get("captcha");
            Date deadline = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse((String) sms.get("deadline"));
            Long expire = (deadline.getTime() - System.currentTimeMillis()) / 1000;
@ -204,27 +198,26 @@ public class LoginService {
            headers.set("Cache-Control", "no-store");
            headers.set("Pragma", "no-cache");
            return new ResponseEntity<>(result, headers, HttpStatus.OK);
        } else {
        }else {
            throw new ManageException("验证码获取失败!");
        }
    }
    /**
     * 管理员手机登录
     *
     *  管理员手机登录
     * @param request
     * @param loginCode 登录名
     * @param loginCode  登录名
     * @return
     * @throws ManageException
     */
    @Transactional(noRollbackForClassName = "ManageException")
    public User managerPhoneLogin(HttpServletRequest request, String loginCode) throws ManageException {
        //判断管理员用户信息是否存在
        User user = userService.findByLoginCodeAAndUserType(loginCode, LoginInfo.USER_TYPE_AdminManager);
        User user = userService.findByLoginCodeAAndUserType(loginCode,LoginInfo.USER_TYPE_AdminManager);
        if (user == null) {
            throw new ManageException("该管理员账号不存在!");
        } else {
        }else {
            //已注册用户更改用户状态
            user.setActivated(HouseUserContant.activated_active);
            request.getSession().setAttribute(LoginInfo.IS_LOGIN, true);
@ -233,29 +226,28 @@ public class LoginService {
            request.getSession().setAttribute(LoginInfo.LOGIN_CODE, user.getLoginCode());
            request.getSession().setAttribute(LoginInfo.USER_ID, user.getId());
            user.setLastLoginTime(new Date());
            userService.saveOrUpdate(user, LoginInfo.SAVE_TYPE_PHONE);
            userService.saveOrUpdate(user,LoginInfo.SAVE_TYPE_PHONE);
        }
        return user;
    }
    /**
     * 管理员-账号密码登录
     *
     *  管理员-账号密码登录
     * @param request
     * @param clientId  应用id
     * @param loginCode 登录账号
     * @param password  密码
     * @param clientId      应用id
     * @param loginCode     登录账号
     * @param password      密码
     * @return
     * @throws ManageException
     */
    @Transactional(noRollbackForClassName = "ManageException")
    public User managerLogin(HttpServletRequest request, String clientId, String loginCode, String password) throws ManageException {
    public User managerLogin(HttpServletRequest request,String clientId, String loginCode, String password) throws ManageException {
        //判断登陆信息是否正确
        User user = userService.findByCode(loginCode);
        if (user == null) {
            String message = "该管理员账号不存在!";
            throw new ManageException(message);
        } else {
        }else {
            if (!user.getPassword().equals(MD5.GetMD5Code(password + user.getSalt()))) {
                String message = "密码错误";
                throw new ManageException(message);

+ 39 - 0
svr/svr-healthy-house/src/main/java/com/yihu/jw/healthyhouse/service/user/UserService.java

@ -87,6 +87,45 @@ public class UserService {
    }
    /**
     *  不分页条件搜索
     * @param map
     * @param order
     * @return
     * @throws ManageException
     */
    public List<User> userList( Map<String, String> map, String order) throws ManageException {
        order = order == null ? "ASC" : order;
        // 排序
        Sort sort = new Sort(Sort.Direction.fromString(order), "facilityUsedCount");
        // 设置查询条件
        Map<String, SearchFilter> filters = new HashMap<String, SearchFilter>();
        // 所在市区
        String cityCode = map.get("cityCode");
        if (!StringUtils.isEmpty(cityCode)) {
            filters.put("cityCode", new SearchFilter("cityCode", SearchFilter.Operator.EQ, cityCode));
        }
        // 激活状态
        String activated = map.get("activated");
        if (!StringUtils.isEmpty(activated)) {
            filters.put("activated", new SearchFilter("activated", SearchFilter.Operator.EQ, activated));
        }
        // 用户名称
        String name = map.get("name");
        if (!StringUtils.isEmpty(name)) {
            filters.put("name", new SearchFilter("name", SearchFilter.Operator.LIKE, name));
        }
        // 电话号码
        String mobile = map.get("telephone");
        if (!StringUtils.isEmpty(mobile)) {
            filters.put("telephone", new SearchFilter("telephone", SearchFilter.Operator.LIKE, mobile));
        }
        Specification<User> spec = DynamicSpecifications.bySearchFilter(filters.values(), User.class);
        return userDao.findAll(spec,sort);
    }
    /**
     * 更改用户状态
     *