need help for downloading my pie chart in CSV

335 views
Skip to first unread message

nishh

unread,
Sep 19, 2012, 1:43:27 AM9/19/12
to google-visua...@googlegroups.com
<apex:page controller="DashPortalController" sidebar="false"> 
    <apex:pageMessages ></apex:pageMessages>
    <!-- Google API inclusion -->
    <apex:includeScript id="a" value="https://www.google.com/jsapi" />
    
    <apex:sectionHeader title="Google Charts" subtitle="Chart 1"/>
    
    <!-- Google Charts will be drawn in this DIV -->
   
    <apex:form >
       <table align="center">
                <td><b>Date From:</b>
                <input id="t" name="datee" onfocus="DatePicker.pickDate(false,'t', false);"
                     size="12" tabindex="28" type="text" />
                     
                     </td><td></td>
                <td></td>
                <td></td>
                <td></td>
                <td><b>Date To:</b>
                <apex:outputText value="{0,date,dd/MM/yyyy}">
                    <apex:param value="{!NOW()}" />
                </apex:outputText></td> 
                <td><button onclick="initCharts()">Go</button></td>
               
        </table>
     </apex:form>    
    <div id="chartBlock" style="width: 500px; height: 500px;"/>
    
    <script type="text/javascript">
        
        google.load('visualization', '1', {'packages':['corechart']});
        google.setOnLoadCallback(initCharts);
   
        function initCharts() { 
        var dateFrom= $('#t').val();        
             DashPortalController.loadCustomerServiceSuccessRate(
                 dateFrom,function(result, event){
                     if (event.status && event.result) {  
                         
             // for each result, apply it to template and append generated markup
             // to the results table body.
            var visualization = new google.visualization.PieChart(document.getElementById('chartBlock'));
                       var data = new google.visualization.DataTable();
                          data.addColumn('string','Success or Failure');
                          data.addColumn('number','Percentage');
                          
                        var finalBean= result;
                           data.addRows([
                      
                      ['Service Success Rate', finalBean.totalServiceColl],
                      ['Service Failure Rate', finalBean.totalCases]]);
                    
        } else {
           alert(event.message);
        }
         
                    visualization.draw(data,{title:'Service Success Rate',legend : {position: 'bottom', textStyle: {color: 'blue', fontSize: 10}}, width:window.innerWidth,vAxis:{textStyle:{color:'red', fontSize: 15}}});
                }, {escape:true}); 
          } 
    </script>
   
</apex:page>

asgallant

unread,
Sep 19, 2012, 10:51:35 AM9/19/12
to google-visua...@googlegroups.com
The easiest way to handle this is usually server-side, but if you want to handle it in javascript, I wrote a hack that will do the job: http://jsfiddle.net/asgallant/MqERY/3/.  The relevant code is near the bottom (see the section beginning with "var runOnce = ...").

nishh

unread,
Sep 20, 2012, 12:16:57 AM9/20/12
to google-visua...@googlegroups.com
thanks for your reply.....as i am not much aware of this variable var=runonce....can u help me for making a csv file for my code as i am picking values from controller in my piechart.
i hope you will help me

asgallant

unread,
Sep 20, 2012, 1:10:45 AM9/20/12
to google-visua...@googlegroups.com
It's this piece of code:

var runOnce google.visualization.events.addListener(table'ready'function ({
    document.getElementById('toCSV').onclick function ({
        var tempData table.getDataTable();
        var csvData [];
        var tmpArr [];
        var tmpStr '';
        for (var 0tempData.getNumberOfColumns()i++{
            // replace double-quotes with double-double quotes for CSV compatibility
            tmpStr tempData.getColumnLabel(i).replace(/"/g'""');
            tmpArr.push('"' tmpStr '"');
        }
        csvData.push(tmpArr);
        for (var 0tempData.getNumberOfRows()i++{
            tmpArr [];
            for (var 0tempData.getNumberOfColumns()j++{
                switch(data.getColumnType(j){
                    case 'string':
                        // replace double-quotes with double-double quotes for CSV compatibility
                        tmpStr tempData.getValue(ij).replace(/"/g'""');
                        tmpArr.push('"' tmpStr '"');
                        break;
                    case 'number':
                        tmpArr.push(tempData.getValue(ij));
                        break;
                    case 'boolean':
                        tmpArr.push((tempData.getValue(ij)'True' 'False');
                        break;
                    case 'date':
                        // decide what to do here, as there is no universal date format
                        break;
                    case 'datetime':
                        // decide what to do here, as there is no universal date format
                        break;
                    case 'timeofday':
                        // decide what to do here, as there is no universal date format
                        break;
                    default:
                        // should never trigger
                }
            }
            csvData.push(tmpArr.join(','));
        }
        var output csvData.join('\n');
        var uri 'data:text/csv;charset=UTF-8,' encodeURIComponent(output);
        alert('You may need to rename the downloaded file with a ".csv" extension to open it.');
        window.open(uri);
    };
    google.visualization.events.removeListener(runOnce);
});

Assuming you are using a dashboard to bind your control and chart together, you will need to put this code after you set up the chart but before you call the dashboard's #draw method.  Replace the "table" variable in this code with the variable that holds your pie chart.  Add an HTML element to your page with the id "toCSV" (or give it another id and change the id in the code) that users can click on to download the data as a csv.  The example uses a button:

<input type="button" id="toCSV" value="Click to download data as CSV" />

If your DataTable has data of type "date", "datetime", or "timeofday", you will have to fill out those sections in the code to output the data in the way you want it, as there is no standard method for handling those data types.

nishh

unread,
Sep 20, 2012, 1:30:03 AM9/20/12
to google-visua...@googlegroups.com
I have used it like this but when i click on download button 
nothing happens
here i have changed table with data.. but  i think its not the correct way or the variable i have used is not correct

the upper code is mine and runonce which u gave me

function initCharts() {
               
              WasteSplit.WasteSource(
                   function(result, event){
                     // load Column chart
                     var visualization = new google.visualization.PieChart(document.getElementById('chartBlock'));
                      // Prepare table model for chart with columns
                       var data = new google.visualization.DataTable();
                       data.addColumn('string', 'Waste Name');
                       data.addColumn('number', 'Waste Type');
                          
                       // add rows from the remoting results
                       for(var i=0; i<result.length;i++){
                        var finalBean= result[i];
                          data.addRow([finalBean.WasteName,finalBean.wastetype]);
                        }
                      // all done, lets draw the chart with some options to make it look nice.
                      visualization.draw(data,{title:'Waste Service Split at Source',legend : {position: 'bottom', textStyle: {color: 'blue', fontSize: 10}}, width:window.innerWidth,vAxis:{textStyle:{color:'red', fontSize: 15}},hAxis:{title: 'Record Count',textStyle:{fontSize: 10},showTextEvery:1,slantedText:true}} );
                }, {escape:true});
                
                 // attach an event handler to the CSV download button
    var runOnce = google.visualization.events.addListener(data, 'ready', function () {
        document.getElementById('toCSV').onclick = function () {
            var tempData = data.getDataTable();   

nishh

unread,
Sep 20, 2012, 2:32:51 AM9/20/12
to google-visua...@googlegroups.com
sorry i have changed data variable with visualization...but nothing happens

asgallant

unread,
Sep 20, 2012, 10:01:53 AM9/20/12
to google-visua...@googlegroups.com
Ahh, you're not using a dashboard.  That's ok, just a small change needed:

var runOnce google.visualization.events.addListener(visualization'ready'function ({
    document.getElementById('toCSV').onclick function ({
        var csvData [];

        var tmpArr [];
        var tmpStr '';
        for (var 0< data.getNumberOfColumns()i++{

            // replace double-quotes with double-double quotes for CSV compatibility
            tmpStr data.getColumnLabel(i).replace(/"/g'""');

            tmpArr.push('"' tmpStr '"');
        }
        csvData.push(tmpArr);
        for (var 0data.getNumberOfRows()i++{
            tmpArr [];
            for (var 0data.getNumberOfColumns()j++{

                switch(data.getColumnType(j){
                    case 'string':
                        // replace double-quotes with double-double quotes for CSV compatibility
                        tmpStr data.getValue(ij).replace(/"/g'""');

                        tmpArr.push('"' tmpStr '"');
                        break;
                    case 'number':
                        tmpArr.push(data.getValue(ij));
                        break;
                    case 'boolean':
                        tmpArr.push((data.getValue(ij)'True' 'False');

                        break;
                    case 'date':
                        // decide what to do here, as there is no universal date format
                        break;
                    case 'datetime':
                        // decide what to do here, as there is no universal date format
                        break;
                    case 'timeofday':
                        // decide what to do here, as there is no universal date format
                        break;
                    default:
                        // should never trigger
                }
            }
            csvData.push(tmpArr.join(','));
        }
        var output csvData.join('\n');
        var uri 'data:text/csv;charset=UTF-8,' encodeURIComponent(output);
        alert('You may need to rename the downloaded file with a ".csv" extension to open it.');
        window.open(uri);
    };
    google.visualization.events.removeListener(runOnce);
}); 

Add that code right before you call visualization.draw(...); 
Reply all
Reply to author
Forward
0 new messages