Google Visualization Datatable to CSV下载 [英] Google Visualization Datatable to CSV download

查看:118
本文介绍了Google Visualization Datatable to CSV下载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我有:


  • Google可视化产品

  • 数据从数据库或表中读取并加载到数据表中。

  • Datatable用于创建Google Visualization图形。 / li>
  • 按钮或链接到下载到CSV,我需要根据
    加载数据的当前配​​置。即毕竟所有的处理和
    变化,包括控制。
    现在我想按下downloadCSV javascript函数与一个数据表(全局不幸的是)与文件名。
    我已经从线程的答案之一下载了代码... 有没有什么方法可以在使用数据时指定建议的文件名uri



    我希望人们发现这有帮助。

    Raven

     < html> 
    < head>
    < script type =text / javascriptsrc =https://www.google.com/jsapi>< / script>
    < script type =text / javascript>
    //从[Visualization:Area Chart]中提取的初始部分[2]

    google.load(visualization,1,{packages:[corechart]});

    google.setOnLoadCallback(drawChart);
    var data;
    $ b函数drawChart(){
    data = google.visualization.arrayToDataTable([
    ['Year','Sales','Expenses'],
    ['' 2004',1000,400],
    ['2005',1170,460],
    ['2006',660,1120],
    ['2007',1030,540]
    ]);

    var options = {
    title:'Company Performance',
    hAxis:{title:'Year',titleTextStyle:{color:'red'}}
    };

    var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
    chart.draw(data,options);


    $ b //附加代码

    函数downloadCSV(文件名){
    jsonDataTable = data.toJSON();
    var jsonObj = eval('('+ jsonDataTable +')');
    output = JSONObjtoCSV(jsonObj,',');
    }

    函数JSONObjtoCSV(jsonObj,文件名){
    filename = filename || download.csv;
    var body =''; var j = 0;
    var columnObj = []; var columnLabel = []; var columnType = [];
    var columnRole = []; var outputLabel = []; var outputList = [];
    for(var i = 0; i< jsonObj.cols.length; i ++){
    columnObj = jsonObj.cols [i];
    columnLabel [i] = columnObj.label;
    columnType [i] = columnObj.type;
    columnRole [i] = columnObj.role;
    if(columnRole [i] == null){
    outputLabel [j] =''+ columnObj.label +''';
    outputList [j] = i;
    j ++;
    }
    }
    body + = outputLabel.join(,)+ String.fromCharCode(13);

    for(var thisRow = 0; thisRow< jsonObj.rows.length; thisRow ++){
    outputData = []; (var k = 0; k< outputList.length; k ++){
    var thisColumn = outputList [k];
    var thisType = columnType [thisColumn];
    thisValue = jsonObj.rows [thisRow] .c [thisColumn] .v;
    switch(thisType){
    case'string':
    outputData [k] =''+ thisValue +''';打破;
    case'datetime':
    thisDateTime = eval(new+ thisValue);
    outputData [k] =''+ thisDateTime.getDate()+' - '+(thisDateTime.getMonth()+ 1)+' - '+ thisDateTime.getFullYear()+''+ thisDateTime.getHours )+':'+ thisDateTime.getMinutes()+':'+ thisDateTime.getSeconds()+''';
    delete window.thisDateTime;
    休息;
    默认值:
    outputData [k] = thisValue;
    }
    }
    body + = outputData.join(,);
    body + = String.fromCharCode(13);
    }
    uriContent =data:text / csv; filename = download.csv,+ encodeURIComponent(body);
    newWindow = downloadWithName(uriContent,'download.csv');
    return(body);
    }

    函数downloadWithName(uri,name){
    // https://stackoverflow.com/questions/283956/is-there-any-way-to-specify -a-suggested-filename-when-data-uri
    function eventFire(el,etype){
    if(el.fireEvent){
    (el.fireEvent('on'+ VLAN时));
    } else {
    var evObj = document.createEvent('Events');
    evObj.initEvent(etype,true,false);
    el.dispatchEvent(evObj);
    }
    }
    var link = document.createElement(a);
    link.download = name;
    link.href = uri;
    eventFire(链接,点击);
    }
    < / script>
    < / head>
    < body>
    < div id =chart_divstyle =width:900px; height:500px;>< / div>
    < button id =CSVDownloadonclick =downloadCSV('download.csv')title =下载到CSV>下载到CSV< / Button>

    < / body>
    < / html>


    解决方案

    我将添加一个更简单的方法将Google表格导出为CSV。您可以使用Google Visualization API。假设你的范围内有一个名为 dataTable 的Google表。然后使用以下代码将其下载为.csv。



    代码:

    <$ (数据表);
    var encodedUri ='data:$($# application / csv; charset = utf-8,'+ encodeURIComponent(csvFormattedDataTable);
    this.href = encodedUri;
    this.download ='table-data.csv';
    this.target ='_blank';
    });

    说明:

    这里的#Export是一个锚点元素,设置为< a id =Exporthref =#>下载为csv< / a> 页。 Google visualization api's

      google.visualization.dataTableToCsv()

    完成将表格对象重新格式化为csv的所有努力。有关详情,请访问 Google Visualization Doc

    在这里,我使用了jQuery选择器 $ 。如果你想在没有jQuery的情况下做到这一点,请替换 $('#Export')。click(function(){// Function define here。}); with document.getElementById(Export)。onclick = function(){//函数定义在这里};



    格式化数据通过上述方法返回,我们利用 download 属性将数据作为csv文件下载,文件名为 table-data (您可以随意命名。



    重要提示:Internet不支持 download 属性这个问题已经通过谷歌浏览器和Mozilla Firefox进行了测试,详情请参阅下载属性


    Adding to Stack Overflow after leeching for long enough.

    What I have:

    • Google Visualization product
    • Data read from database or table and loaded into datatable.
    • Datatable is used to create Google Visualization graphics.
    • Button or link to "Download to CSV" which I need to be loaded as per the current configuration of the data. I.e. after all processing and changes, including controls.

    Now I want to press the downloadCSV javascript function with a datatable (global unfortunately) with the filename. I have taken the download code from one of the answers from the thread... is there any way to specify a suggested filename when using data uri

    I hope people find this helpful.

    Raven

    <html>
      <head>
        <script type="text/javascript" src="https://www.google.com/jsapi"></script>
        <script type="text/javascript">
        // Initial Part extracted from [Visualization: Area Chart][2]
    
          google.load("visualization", "1", {packages:["corechart"]});
    
          google.setOnLoadCallback(drawChart);
          var data;
    
          function drawChart() {
            data = google.visualization.arrayToDataTable([
              ['Year', 'Sales', 'Expenses'],
              ['2004',  1000,      400],
              ['2005',  1170,      460],
              ['2006',  660,       1120],
              ['2007',  1030,      540]
            ]);
    
            var options = {
              title: 'Company Performance',
              hAxis: {title: 'Year',  titleTextStyle: {color: 'red'}}
            };
    
            var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
            chart.draw(data, options);
          }
    
    
    // Additional Code
    
        function downloadCSV(filename) {
            jsonDataTable = data.toJSON();
            var jsonObj = eval('(' + jsonDataTable + ')'); 
            output = JSONObjtoCSV(jsonObj,',');
        }
    
        function JSONObjtoCSV(jsonObj, filename){
        filename = filename || 'download.csv';
            var body = '';      var j = 0;
            var columnObj = []; var columnLabel = []; var columnType = [];
            var columnRole = [];    var outputLabel = []; var outputList = [];
            for(var i=0; i<jsonObj.cols.length; i++){
                columnObj = jsonObj.cols[i];
                columnLabel[i] = columnObj.label;
                columnType[i] = columnObj.type;
                columnRole[i] = columnObj.role;
                if (columnRole[i] == null) {
                    outputLabel[j] = '"' + columnObj.label + '"';
                    outputList[j] = i;
                    j++;
                }           
            }
            body += outputLabel.join(",") + String.fromCharCode(13);
    
            for(var thisRow=0; thisRow<jsonObj.rows.length; thisRow++){
                outputData = [];
                for(var k=0; k<outputList.length; k++){
                    var thisColumn = outputList[k];
                    var thisType = columnType[thisColumn];
                    thisValue = jsonObj.rows[thisRow].c[thisColumn].v;
                    switch(thisType) {
                        case 'string':
                            outputData[k] = '"' + thisValue + '"'; break;
                        case 'datetime':
                            thisDateTime = eval("new " + thisValue);
                            outputData[k] = '"' + thisDateTime.getDate() + '-' + (thisDateTime.getMonth()+1) + '-' + thisDateTime.getFullYear() + ' ' + thisDateTime.getHours() + ':' + thisDateTime.getMinutes() + ':' + thisDateTime.getSeconds() + '"';  
                            delete window.thisDateTime;
                            break;
                        default:
                            outputData[k] = thisValue;
                    }
                }
                body += outputData.join(",");
                body += String.fromCharCode(13);
            }       
            uriContent = "data:text/csv;filename=download.csv," + encodeURIComponent(body);
            newWindow=downloadWithName(uriContent, 'download.csv');
            return(body);
        }
    
        function downloadWithName(uri, name) {
         // https://stackoverflow.com/questions/283956/is-there-any-way-to-specify-a-suggested-filename-when-using-data-uri
        function eventFire(el, etype){
            if (el.fireEvent) {
                (el.fireEvent('on' + etype));
            } else {
                var evObj = document.createEvent('Events');
                evObj.initEvent(etype, true, false);
                el.dispatchEvent(evObj);
            }
        }
        var link = document.createElement("a");
        link.download = name;
        link.href = uri;
        eventFire(link, "click");
        }
        </script>
      </head>
      <body>
        <div id="chart_div" style="width: 900px; height: 500px;"></div>
            <button id="CSVDownload" onclick="downloadCSV('download.csv')" title="Download to CSV">Download to CSV</Button>
    
      </body>
    </html>
    

    解决方案

    I'm going to add a slightly simpler way to do export a google table to CSV. You can use Google Visualization api. Suppose you have the google table called dataTable in your scope. Then use the following code to download it as .csv.

    Code:

    $('#Export').click(function () {
            var csvFormattedDataTable = google.visualization.dataTableToCsv(dataTable);
            var encodedUri = 'data:application/csv;charset=utf-8,' + encodeURIComponent(csvFormattedDataTable);
            this.href = encodedUri;
            this.download = 'table-data.csv';
            this.target = '_blank';
        });
    

    Explanation:

    Here #Export is an anchor element set up as <a id="Export" href="#">Download as csv</a> in your page. Google visualization api's

    google.visualization.dataTableToCsv()
    

    does all the hard work of reformatting the table object as csv. More information on this at Google Visualization Doc.

    Here I'm using jQuery selector $. If you want to do this without jQuery, replace $('#Export').click(function () { // Function definition here.}); with document.getElementById("Export").onclick = function() { // function definition here};

    Once the csv formatted data is returned by the method above, we leverage download attribute to download the data as a csv file with the file name table-data (you can name this whatever you like.

    Important: download attribute is not supported by Internet Explorer at the time of this answer. This has been tested with Google Chrome and Mozilla Firefox. For more information download attribute .

    这篇关于Google Visualization Datatable to CSV下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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