jira项目导出chrome插件开发

jira的导出功能,较为鸡肋:导出的csv文件使用excel打开会是乱码,有些内容也不能选为导出字段......
本文为大家介绍一种使用chrome插件,为jira页面添加一个悬浮导出按钮的技术实现方案。


image.png

image.png

原理:

向jira页面添加div元素,并设置好点击处理函数;
当点击导出按钮时:

使用jquery获取jira项目的列表,进一步获取到项目详情;
整理出所需导出的内容;
使用js-xlsx库,将以上数据处理成excel文件并下载。

插件的打包文件如下:


image.png

manifest.json:

{
  "name": "jira国际化项目自动导出excel",
  "manifest_version": 2,
  "version": "1.0",
  "description": "jira国际化项目自动导出excel",
  "browser_action": {
    "default_icon": "jira.png"
  },
  "content_scripts": [
    {
      "matches": ["https://jira.p1staff.com/*"],
      "js": ["jquery.min.js", "xlsx.core.min.js", "jira.js"]
    }
  ]
}

jira.js:

    // 将一个sheet转成最终的excel文件的blob对象,然后利用URL.createObjectURL下载
    function sheet2blob(sheet, sheetName) {
        sheetName = sheetName || 'sheet1';
        var workbook = {
            SheetNames: [sheetName],
            Sheets: {}
        };
        workbook.Sheets[sheetName] = sheet;
        // 生成excel的配置项
        var wopts = {
            bookType: 'xlsx', // 要生成的文件类型
            bookSST: false, // 是否生成Shared String Table,官方解释是,如果开启生成速度会下降,但在低版本IOS设备上有更好的兼容性
            type: 'binary'
        };
        var wbout = XLSX.write(workbook, wopts);
        var blob = new Blob([s2ab(wbout)], {type:"application/octet-stream"});
        // 字符串转ArrayBuffer
        function s2ab(s) {
            var buf = new ArrayBuffer(s.length);
            var view = new Uint8Array(buf);
            for (var i=0; i!=s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
            return buf;
        }
        return blob;
    }

    /**
     * 通用的打开下载对话框方法,没有测试过具体兼容性
     * @param url 下载地址,也可以是一个blob对象,必选
     * @param saveName 保存文件名,可选
     */
    function openDownloadDialog(url, saveName)
    {
        if(typeof url == 'object' && url instanceof Blob)
        {
            url = URL.createObjectURL(url); // 创建blob地址
        }
        var aLink = document.createElement('a');
        aLink.href = url;
        aLink.download = saveName || ''; // HTML5新增的属性,指定保存文件名,可以不要后缀,注意,file:///模式下不会生效
        var event;
        if(window.MouseEvent) event = new MouseEvent('click');
        else
        {
            event = document.createEvent('MouseEvents');
            event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
        }
        aLink.dispatchEvent(event);
    }
function dateFormat(fmt, date) {
    let ret;
    const opt = {
        "Y+": date.getFullYear().toString(),        // 年
        "m+": (date.getMonth() + 1).toString(),     // 月
        "d+": date.getDate().toString(),            // 日
        "H+": date.getHours().toString(),           // 时
        "M+": date.getMinutes().toString(),         // 分
        "S+": date.getSeconds().toString()          // 秒
        // 有其他格式化字符需求可以继续添加,必须转化成字符串
    };
    for (let k in opt) {
        ret = new RegExp("(" + k + ")").exec(fmt);
        if (ret) {
            fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
        };
    };
    return fmt;
}


var div = document.createElement("div");
div.innerHTML = "导出国际化项目";
var css = "position:fixed;top:30px;right:5px;z-index:999999999;line-height:22px;color: white;text-align: center;cursor: pointer;border-radius: 50%;width: 154px;height: 22px;background-color: rgb(252, 157, 154);font-weight: bolder;display: block;";
div.style.cssText = css;
div.title = "点击导出excel";
if(window.self === window.top){ document.body.appendChild(div);}

div.addEventListener("click",function(){
    var cnt = 0;
    var ret = [["summary","key","创建日期","开发预期完成时间","测试预期完成时间","项目经理","产品经理","开发人员","测试人员"]];
    $.ajax({
        url:'/rest/issueNav/1/issueTable',
        type:'post',
        data:'jql=project+%3D+%22GLOB%22+AND+resolution+%3D+Unresolved+ORDER+BY+priority+ASC%2C+updated+DESC&columnConfig=explicit&layoutKey=split-view&startIndex=0',
        success: data => {
            //console.log(JSON.stringify(data));
            cnt = data.issueTable.issueKeys.length;
            data.issueTable.issueKeys.forEach(iss => {
                $.ajax({
                    url:'/rest/api/2/issue/' + iss,
                    type:'get',
                    success: detail => {
                        var dev = "";
                        var qa = "";
                        detail.fields.customfield_11527 && detail.fields.customfield_11527.forEach(one => {dev += one.displayName + ", "});
                        detail.fields.customfield_11528 && detail.fields.customfield_11528.forEach(one => {qa += one.displayName + ", "});
                        ret.push([detail.fields.summary,
                        detail.key,
                            dateFormat("YYYY-mm-dd", new Date(detail.fields.created)),
                            detail.fields.customfield_11523,
                            detail.fields.customfield_13405,
                            detail.fields.customfield_11005 ? detail.fields.customfield_11005.displayName : "-",
                            detail.fields.customfield_11006 ? detail.fields.customfield_11006.displayName : "-",
                            dev,
                            qa
                            ]);
                        cnt--;
                        if (0 == cnt) {
                            //console.log(JSON.stringify(ret));
                            var sheet = XLSX.utils.aoa_to_sheet(ret);
                            for (var i = ret.length - 1; i > 0; i--) {
                                sheet['B'+(i + 1)].l = {Target:'https://jira.p1staff.com/browse/' + ret[i][1]};
                            }
                            openDownloadDialog(sheet2blob(sheet), 'jira国际化项目.xlsx');
                        }
                    }
                });
            });
        }
    });
});

其它的文件,请下载后放置在目录中
https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js
https://demo.haoji.me/2017/02/08-js-xlsx/js/xlsx.core.min.js

你可能感兴趣的:(jira项目导出chrome插件开发)