json转换成excel在线js小工具分享

来源:互联网 发布:淘宝老客户营销短信 编辑:程序博客网 时间:2024/05/16 12:20

起因

我们在工作过程中,偶尔会有需求是把json转换成excel的需求。一般这个时候,我们会跑到度娘那,在输入框中输入:“json excel”。然后,你会发现这个一个网站“https://json-csv.com/”,
出现在结果的第一个位置。
image

进去用了一下,很好用。收藏了。但是过几天,又要用的时候,忽然发现,导不出excel了。盯着上面的英文看了一会。发现这TMD的网站,居然对文件大小进行了限制。必须注册,收费才能上传大于1m以上的文件。@###%$%&^&^*%^%
image

这个功能对于我来说,并非刚需,也是偶发的。而且感觉也不会太难,于是就起了自己做一个“在线小工具”的念头。放开大小限制,让大伙痛快的用。
image

操作也是差不多,支持直接输入json和文件上传。可以导出xls,也可以导出xlsx。如果你的数据比较多的话,建议使用firefox浏览器,导出为xlsx。之所以建议你用导出xlsx,是因为如果导出的行数超过6w的话,xls是不支持的。而推荐使用firefox的原因是因为我的代码实现方式,需要用到dataURI。各个浏览器,对它的大小有限制。firefox则是无限制。使用它导出15M的json,都是秒级的,很快。

大家可以体验下http://j2e.kpoda.com/

硬货

以下是主要代码

function exportJson2Excel(json, type) {      //TODO 记录导出操作日志      var log = {"type": "json2excel"};//title      try {        var title = new Set();        for (var i = 0; i < json.length; i++) {          var r = json[i];          getProFromObject(r, title);        }        console.log("title", title);        var data = [];        for (var i = 0; i < json.length; i++) {          var r = json[i];          var dataRow = [];          title.forEach(function (t) {            var d1 = r[t];            var ss = t.split(".");            if (ss.length >= 2) {              var tmp = r;              for (var i = 0; i < ss.length; i++) {                var s = ss[i];                tmp = tmp[s];                if (!tmp) {                  break;                }              }              d1 = tmp;            }            if (d1) {              if (typeof d1 == 'object') {                dataRow.push(JSON.stringify(d1));              } else {                dataRow.push(d1);              }            } else {              dataRow.push("");            }          });          data.push(dataRow);        }        console.log("data", data);        jsonToExcelConvertor(data, 'Report', Array.from(title), type);      } catch (err) {        console.error(err);        alert("导出报错:" + err.stack);        log.error = err.stack;        log.json =  json;      } finally {        OplogsService.save(log).$promise.then(function (res) {          console.log(res);        }).catch(function (error) {          console.log(error);          alert("系统错误:" + JSON.stringify(error));        });      }    }

getProFromObject方法用来获取json对象的属性,其对应excel的列。其中用到了递归。

function getProFromObject(r, title, parentsPros) {      for (var rp in r) {        if (parentsPros) {          title.add(parentsPros + "." + rp);        } else {          title.add(rp);        }        if (typeof r[rp] == 'object') {          if (parentsPros) {            getProFromObject(r[rp], title, parentsPros + "." + rp);          } else {            getProFromObject(r[rp], title, rp);          }        }      }    }

jsonToExcelConvertor方法用于把整理好的数据,转换为DataURI,输出excel。

function jsonToExcelConvertor(JSONData, FileName, ShowLabel, type) {      type = type ? type : "xls";      var application = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";      if (type == "xls") {        application = "application/vnd.ms-excel";      }      // 先转化json      var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;      var excel = '<table>';      // 设置表头      var rr = '<tr>';      for (var j = 0, l = ShowLabel.length; j < l; j++) {        rr += '<td>' + ShowLabel[j] + '</td>';      }      // 换行      excel += rr + '</tr>';      // 设置数据      for (var i = 0; i < arrData.length; i++) {        var row = '<tr>';        for (var index = 0; index < arrData[i].length; index++) {          var value = arrData[i][index] === '.' ? '' : arrData[i][index];          row += '<td>' + value + '</td>';        }        excel += row + '</tr>';      }      excel += '</table>';      var excelFile = '<html xmlns:o=\'urn:schemas-microsoft-com:office:office\' xmlns:x=\'urn:schemas-microsoft-com:office:excel\' xmlns=\'http://www.w3.org/TR/REC-html40\'>';      excelFile += '<meta http-equiv="content-type" content="' + application + '; charset=UTF-8">';      excelFile += '<meta http-equiv="content-type" content="' + application;      excelFile += '; charset=UTF-8">';      excelFile += '<head>';      excelFile += '<!--[if gte mso 9]>';      excelFile += '<xml>';      excelFile += '<x:ExcelWorkbook>';      excelFile += '<x:ExcelWorksheets>';      excelFile += '<x:ExcelWorksheet>';      excelFile += '<x:Name>';      excelFile += '{worksheet}';      excelFile += '</x:Name>';      excelFile += '<x:WorksheetOptions>';      excelFile += '<x:DisplayGridlines/>';      excelFile += '</x:WorksheetOptions>';      excelFile += '</x:ExcelWorksheet>';      excelFile += '</x:ExcelWorksheets>';      excelFile += '</x:ExcelWorkbook>';      excelFile += '</xml>';      excelFile += '<![endif]-->';      excelFile += '</head>';      excelFile += '<body>';      excelFile += excel;      excelFile += '</body>';      excelFile += '</html>';      var uri = 'data:' + application + ';charset=utf-8,' + encodeURIComponent(excelFile);      var link = document.createElement('a');      link.href = uri;      //TODO Cannot set property style of #<HTMLElement> which has only a getter      // link.style = 'visibility:hidden';      $(link).css("visibility", "hidden");      // link.download = FileName + '.'+type;      $(link).attr("download", FileName + '.' + type);      document.body.appendChild(link);      link.click();      document.body.removeChild(link);    }
原创粉丝点击