前端导出CSV数据格式

2021-03-15  本文已影响0人  为了_理想
 <button onclick="render.exportButton('exportPage')">导出当前页</button>
 <button onclick="render.exportButton('exportClick')">导出所选</button>

  //点击导出
        exportButton: function (str) {
            var strType = "exportClick"
            var constarr = []
            render.arrList.data.forEach(function (item, index) {
                if(str === strType){ 
                    if (item.chose) {
                    constarr.push(render.setDownParams(item))
                 }
                }else{ 
                    constarr.push(render.setDownParams(item))
                }
            })
            if(constarr.length==0){ 
                layer.msg("没有可导出的数据")
                return false
            }
            render.downExcal(constarr)
        },
      
        //处理需要打印的字段
        setDownParams:function(item){ 
            var strArray = ["location",'shape','weight',"color","intensity",
                           "clarity","cut","polish","symmetry","fluor","milk",
                           "coffee","certificate_number","global_price","carats_price",
                           "dia_discount","goods_price","user_price","dia_size","dia_table","dia_depth"]
            var params = {}
            for(var i=0;i<strArray.length;i++){ 
                params[strArray[i]] = item[strArray[i]]
            }
            params.certificate_number = item.certificate_type + ' ' + item.certificate_number
            params.dia_table = item.dia_table <= 0 ? '--' : item.dia_table
            params.dia_depth = item.dia_depth <= 0 ? '--' : item.dia_depth
                 if(render.params.type == 1){
                    delete params.dia_discount
                }else{ 
                    delete params.intensity
                }
            return params
        },

        downExcal: function (constarr) {
            //定义表头
            var str = ""
            if(render.params.type == 1){ 
                str = `所在地,形状,重量,颜色,强度,净度,切工,抛光,对称,荧光,奶色,咖色,证书号,国际报价,人民币,每粒单价,会员价,尺寸,台宽比,全深比\n`;
            }else{ 
                str = `所在地,形状,重量,颜色,净度,切工,抛光,对称,荧光,奶色,咖色,证书号,国际报价,人民币,折扣,每粒单价,会员价,尺寸,台宽比,全深比\n`;
            }
            //增加\t为了不让表格显示科学计数法或者其他格式
            var data = constarr
            for (var i = 0; i < data.length; i++) {
                for (var item in data[i]) {
                    str += `${data[i][item] + '\t'},`;
                }
                str += '\n';
            }
            //encodeURIComponent解决中文乱码
            var uri = 'data:text/csv;charset=utf-8,\ufeff' + encodeURIComponent(str);
            //通过创建a标签实现
            var link = document.createElement("a");
            link.href = uri;
            //对下载的文件命名
            link.download = `${'导出裸钻数据' || '表格数据'}.csv`;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        },

导出之后的样子

微信截图_20210315111613.png
上一篇 下一篇

猜你喜欢

热点阅读