如何将Javascript数组转换为CSV文件并从Chrome扩展程序下载?

时间:2018-04-02 12:00:04

标签: javascript angularjs google-chrome-extension export-to-csv

您好我是Chrome Extension新手并在angularjs中进行开发,我正在尝试将数组转换为csv文件并从Chrome扩展程序下载。

我试过

    protected void Page_Load(object sender, EventArgs e)
        {
        footerYear.Text = DateTime.Now.Year.ToString();

        if (!IsPostBack)
        {
            if (Context.User.Identity.IsAuthenticated)
            {
                if (Context.User.IsInRole("student"))
                {
                   HyperLink1.Visible = false;
                    Label1.Text = "Hi " + Context.User.Identity.Name + "!";
           }

                else if (Context.User.IsInRole("teacher"))
                {
                    HyperLink1.Visible = false;
                    Label1.Text = "Hi " + Context.User.Identity.Name + "!";

                }

                else if (Context.User.IsInRole("registrar"))
                {
                    Label1.Text = "Hi " + Context.User.Identity.Name + "!";
                    HyperLink1.Visible = false;
                }
            }

            else if (!Context.User.Identity.IsAuthenticated)
            {
                Label1.Text = "Hi Guest!";
            }

        } 

然后我从SO

获得另一种方法
var csvData = new Blob($scope.result, { type: 'text/csv' }); 
var csvUrl = URL.createObjectURL(csvData);
chrome.downloads.download({ url: csvUrl });     

但是他们两个都没有正常工作,我在manifest.json

中有以下许可
    var finalVal = '';

    for (var i = 0; i < $scope.result.length; i++) {
        var value = $scope.result[i];

        for (var j = 0; j < value.length; j++) {
            var innerValue =  value[j]===null?'':value[j].toString();
            var result = innerValue.replace(/"/g, '""');
            if (result.search(/("|,|\n)/g) >= 0)
                result = '"' + result + '"';
            if (j > 0)
                finalVal += ',';
            finalVal += result;
        }

        finalVal += '\n';
    }

    console.log(finalVal);

    var download = document.getElementById('download');
    download.setAttribute('href', 'data:text/csv;charset=utf-8,' + encodeURIComponent(finalVal));
    download.setAttribute('download', 'test.csv');

虽然第一种方法下载文件但它包含

permissions": [
        "http://*/*",
        "https://*/*",
        "unlimitedStorage",
        "contextMenus",
        "cookies",
        "tabs",
        "notifications",
        "activeTab",
        "downloads",
        "background"
    ]

我需要将 $ scope.result 导出到csv文件中

1 个答案:

答案 0 :(得分:0)

尝试

var csvData = new Blob(JSON.stringify($scope.result), { type: 'text/csv' }); 
var csvUrl = URL.createObjectURL(csvData);
chrome.downloads.download({ url: csvUrl });