Angular导出Excel客户端 [英] Angular export Excel client side

查看:92
本文介绍了Angular导出Excel客户端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Angular v4,我想我该如何从组件中的对象开始构建Excel电子表格.我需要单击一个按钮来下载Excel文件,并且必须在客户端进行此操作.我有一个由数组组成的json文件,我需要将此文件传输到excel文件中,该文件可能在样式上可以自定义.是否有可能?如果是,怎么办?

I'm using Angular v4, i guess how can I build an Excel spreadsheet starting from an object in a component. I need to download the Excel file on the click of a button and I have to do this client side. I have a json file composed of arrays and I need to transfer this on an excel file, possibly customizable in style. Is it possible? If yes, how?

请不要js库,需要使用Typescript和Angular完成此操作

No js libraries please, need to do this with Typescript and Angular

推荐答案

yourdata = jsonData

yourdata= jsonData

ConvertToCSV(objArray) {
            var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
              var str = '';
            var row = "";

            for (var index in objArray[0]) {
                //Now convert each value to string and comma-separated
                row += index + ',';
            }
            row = row.slice(0, -1);
            //append Label row with line break
            str += row + '\r\n';

            for (var i = 0; i < array.length; i++) {
                var line = '';
                for (var index in array[i]) {
                    if (line != '') line += ','

                    line += array[i][index];
                }
                str += line + '\r\n';
            }
            return str;
        }

在您的html中:

<button (click)="download()">export to excel</button>

在组件中:

download(){    
 var csvData = this.ConvertToCSV(yourdata);
                        var a = document.createElement("a");
                        a.setAttribute('style', 'display:none;');
                        document.body.appendChild(a);
                        var blob = new Blob([csvData], { type: 'text/csv' });
                        var url= window.URL.createObjectURL(blob);
                        a.href = url;
                        a.download = 'User_Results.csv';/* your file name*/
                        a.click();
                        return 'success';
}

希望您能为您提供帮助

这篇关于Angular导出Excel客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆