獲取釘釘打卡數據並導出Excel

<dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel</artifactId>
            <version>2.2.3</version>
        </dependency>

        <dependency>
            <groupId>com.taobao.top</groupId>
            <artifactId>taobao-sdk-java-auto</artifactId>
            <version>1.0.0</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/src/main/resources/lib/taobao-sdk-java-auto_1479188381469-20200512.jar</systemPath>
        </dependency>
        <dependency>
            <groupId>com.taobao.top</groupId>
            <artifactId>taobao-sdk-java-auto-source</artifactId>
            <version>1.0.0</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/src/main/resources/lib/taobao-sdk-java-auto_1479188381469-20200512-source.jar</systemPath>
        </dependency>
 

import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.write.style.HeadRowHeight;
import lombok.Data;

import java.io.Serializable;


/**
 * @author wongH
 * @date 2020/5/26 10:39
 * @Version 1.0
 */
@Data
@HeadRowHeight(value = 40)
public class ExcelModel  implements Serializable {

    @ExcelProperty(value = {"姓名"}, index = 0)
    private String name;

    @ExcelProperty(value = {"用戶id"}, index = 1)
    private String userId;

    @ExcelProperty(value = {"考勤組"}, index = 2)
    private String groupId;

    @ExcelProperty(value = {"上下班"}, index = 3)
    private String checkType;

    @ExcelProperty(value = {"時間"}, index = 4)
    private String checkTime;

    @Override
    public boolean equals(Object o) {
        if (o instanceof ExcelModel) {
            ExcelModel excelModel = (ExcelModel) o;
            return this.name.equals(excelModel.name)
                    && this.userId.equals(excelModel.userId)
                    && this.groupId.equals(excelModel.groupId)
                    && this.checkType.equals(excelModel.checkType)
                    && this.checkTime.equals(excelModel.checkTime);
        }
        return super.equals(o);
    }
}

 

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.HorizontalAlignment;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;

/**
 * @author wongH
 * @date 2020/5/26 11:31
 * @Version 1.0
 */
@Slf4j
public class ExcelUtil {
    /**
     * 導出
     * @param response
     * @param data
     * @param fileName
     * @param sheetName
     * @param clazz
     * @throws Exception
     */
    public static void writeExcel(HttpServletResponse response, List<? extends Object> data,
                                  String fileName, String sheetName, Class clazz) throws Exception {
        //表頭樣式
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        //設置表頭居中對齊
        headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        //內容樣式
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        //設置內容居中對齊
        contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);

        HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);

        EasyExcel.write(getOutputStream(fileName, response), clazz)
                .excelType(ExcelTypeEnum.XLSX)
                .sheet(sheetName)
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                .registerWriteHandler(horizontalCellStyleStrategy)
                .doWrite(data);
    }
    private static OutputStream getOutputStream(String fileName, HttpServletResponse response) throws Exception {
        fileName = URLEncoder.encode(fileName, "UTF-8");
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
        return response.getOutputStream();
    }
}



 

import com.alibaba.fastjson.JSONObject;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.*;
import com.dingtalk.api.response.*;
import com.taobao.api.ApiException;
import fangrong.com.cn.conmmon.ExcelUtil;
import fangrong.com.cn.entity.ExcelModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

import static fangrong.com.cn.config.DingdingConfig.AccessToken;

@RequestMapping("/")
@RestController
@Slf4j
public class IndexController {

    @GetMapping("")
    public void getData(HttpServletResponse response) throws Exception {
        //獲取部門用戶id列表  後期可以改成 下面的getUserIdsPage()方法 查詢全部在職的員工id
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/getDeptMember");
        OapiUserGetDeptMemberRequest req = new OapiUserGetDeptMemberRequest();
        //需要查詢的部門
        req.setDeptId("142921000");
        req.setHttpMethod("GET");
        OapiUserGetDeptMemberResponse rsp = client.execute(req, AccessToken);
        List<String> userIds = rsp.getUserIds();

        //獲取用戶打卡記錄
        long i = 0L;
        List<ExcelModel> excelModels = new ArrayList<>();
        while (true) {
            //獲取userIds 指定日期內的打卡記錄
            DingTalkClient client1 = new DefaultDingTalkClient("https://oapi.dingtalk.com/attendance/list");
            OapiAttendanceListRequest req1 = new OapiAttendanceListRequest();
            req1.setWorkDateFrom("2020-01-06 00:00:00");
            req1.setWorkDateTo("2020-01-11 00:00:00");
            //最大50個
            req1.setUserIdList(userIds);
            req1.setOffset(i);
            req1.setLimit(50L);
            log.warn(String.valueOf(i));
            OapiAttendanceListResponse rsp1 = client1.execute(req1, AccessToken);
            List<OapiAttendanceListResponse.Recordresult> recordresults = rsp1.getRecordresult();
            if (recordresults.isEmpty()) {
                break;
            }
            //打卡結果封裝
            for (OapiAttendanceListResponse.Recordresult recordresult : recordresults) {
                String userId = recordresult.getUserId();
                //根據id獲取用戶詳情
                JSONObject userInfo = getUserInfo(userId);
                String onDuty = recordresult.getCheckType().equals("OnDuty") ? "上班" : "下班";
                Date userCheckTime = recordresult.getUserCheckTime();
                LocalDateTime localDateTime = LocalDateTime.ofInstant(userCheckTime.toInstant(), ZoneId.systemDefault());
                DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                String checkTime = localDateTime.format(dtf);
                //封裝數據ExcelModel
                ExcelModel excelModel = new ExcelModel();
                excelModel.setName(userInfo.getString("name"));
                excelModel.setUserId(userId);
                excelModel.setCheckType(onDuty);
                //獲取考勤組名稱
                excelModel.setGroupId(getAttendance(recordresult.getGroupId()));
                excelModel.setCheckTime(checkTime);
                if (!excelModels.contains(excelModel)) {
                    excelModels.add(excelModel);
                }
            }
            i += 50;
        }
        String fileName = "考勤";
        String sheetName = "考勤";
        try {
            ExcelUtil.writeExcel(response, excelModels, fileName, sheetName, ExcelModel.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 查詢用戶信息
     *
     * @param userId 用戶id
     */
    public static JSONObject getUserInfo(String userId) {
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/get");
            OapiUserGetRequest req = new OapiUserGetRequest();
            req.setUserid(userId);
            req.setHttpMethod("GET");
            OapiUserGetResponse rsp = client.execute(req, AccessToken);
            return JSONObject.parseObject(rsp.getBody());
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 查詢考勤組名稱
     *
     * @param id 考勤組id
     */
    public static String getAttendance(Long id) {
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/attendance/group/query");
        OapiAttendanceGroupQueryRequest req = new OapiAttendanceGroupQueryRequest();
        req.setOpUserId("manager01");
        req.setGroupId(id);
        try {
            OapiAttendanceGroupQueryResponse rsp = client.execute(req, AccessToken);
            return rsp.getResult().getName();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 查詢全部在職用戶Id
     *
     * @param status     在職員工子狀態篩選,其他狀態無效。2:試用期;3:正式;5:待離職;-1:無狀態。
     * @param nextCursor 下一次調用需要傳的分頁值
     * @param set        調用這個方法的外部set集合 如 Set<String> set = new HashSet<>() ; 自動將全部id封裝到這個set中
     */
    public static void getUserIdsPage(String status, Long nextCursor, Set<String> set) {
        JSONObject jsonObject = getUserIds(status, nextCursor);
        List<String> dataList = (List<String>) jsonObject.get("dataList");
        set.addAll(dataList);
        Long cursor = jsonObject.getLong("cursor");
        if (cursor != null) {
            getUserIdsPage(status, cursor, set);
        }
    }

    private static JSONObject getUserIds(String status, Long nextCursor) {
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/smartwork/hrm/employee/queryonjob");
            OapiSmartworkHrmEmployeeQueryonjobRequest req = new OapiSmartworkHrmEmployeeQueryonjobRequest();
            req.setStatusList(status);
            req.setOffset(nextCursor);
            req.setSize(50L);
            OapiSmartworkHrmEmployeeQueryonjobResponse rsp = client.execute(req, AccessToken);
            List<String> dataList = rsp.getResult().getDataList();
            Long cursor = rsp.getResult().getNextCursor();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("dataList", dataList);
            jsonObject.put("cursor", cursor);
            return jsonObject;
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return null;
    }


    public static void main(String[] args) {
        Set<String> set = new HashSet<>();
        getUserIdsPage("3", 0L, set);
        System.err.println("一共有===>" + set.size());
    }


}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章