Export Dojo Datagrid Results to .csv File?

7366
23
01-09-2012 05:50 AM
EmilyLaMunyon
Occasional Contributor
Hello,

Does anyone have advice on how to export the contents of a dojo.datagrid to a .csv file or excel spreadsheet? I am needing this function in my Javascript API web mapping application.

Thanks!
0 Kudos
23 Replies
TracySchloss
Frequent Contributor
I decided it was the fact that I was pushing values into an array, along with my row return that was causing my data to 'shift' over one column.  Instead of each row of data ending in just '\r', it was ending as \r , (newline followed by a comma).  This meant the first string value after the new line was a comma, which forced the whole row over one place.

I ended up writing a global replacement for \r ,  (new row comma) , replacing it with just new row.
var inputData = data.replace(/\n,/g, "\n");//some clean up to get rid of the leading commas in the data
0 Kudos
ThomasHynes
New Contributor III
This worked perfectly with very little additional coding.  Just wanted to add that instead of pulling results from the DataGrid, I pulled the data from custom graphics layer that is managed by the grid.

Thanks Mark for http://gis.stackexchange.com/questions/67862/export-dojo-datagrid-results-to-csv-in-javascript-web-a...
0 Kudos
TracySchloss
Frequent Contributor
I'm trying to update my code to AMD style.  First I thought I could also switch from dojox/grid/dataGrid to dGrid/enhancedGrid.  I'm not sure my problem is related to the type of grid I'm using.  But I am having so many problems, I decided to leave it as my original grid type for now. 

This feels very close to the AMD version of what I posted earlier.  But this version doesn't work.  I can get all the way to the point where I can see my data formatted as a long string with the line returns in it.  But the part where I use the form to submit the action to the csv.ashx fails.  I'm getting an error 405 - HTTP verb used to access this page is not allowed.
The page you are looking for cannot be displayed because an invalid method (HTTP verb) was used to attempt access.

This is titlePane section
<div id="tp_print" data-dojo-type="dijit/TitlePane" data-dojo-props="title:'Print Options', closable:false, open:false">
<div>
<form data-dojo-type="dijit/form/Form" method="post" action="" style="height: 0px; width: 0px; display:none;" class="dlform" id="downloadForm" target="_blank">
<input type="hidden" name="report" class="ri" id="reportinput" value="" />
<input type="hidden" name="filename" class="fn" id="filename" value="" />
<input type="hidden" name="s" class="s" id="s" value="" />
<input type="hidden" name="numberofcolumns" class="rit" id="numberofcolumns" value="pdf" />
</form>
 <button id="btnExportGridCSV" data-dojo-type="dijit/form/Button" data-dojo-props="title:'Save Search Results to CSV file', label:'Save List'"></button>  
</div>

</div>


I have a click event added to the button btnExportGridCSV, which executes this function
//functions for printing
function exportGridCSV() {//creates a CSV file that can be saved by the user
    var fieldValue = "";
    dataArray.length = 0;
    arrayUtil.forEach(qTaskNameList, function(gridName) {
        dataArray.length = 0;
        var gridData = registry.byId(gridName+"_grid");
        var gridLength = gridData.rowCount;
        var fields = gridData.layout.cells;
        fieldNames.length = 0;
        //populates an array with the field names used to find the values in the data store
        if (fields.length > 0){
         arrayUtil.forEach(fields, function (field) {     
            if (field.name) {        //this skips the internal IDs, which don't have names 
                var lastField = fields[fields.length -1].name;
                var fName = field.name;         
                fieldNames.push(fName);
                if (fName != lastField) {
                dataArray.push(fName);
                } else {
                dataArray.push(fName+" \n");    
                }               
            }
         });
        }
        if (gridLength > 0) {//don't try to export if there were not values in that grid
        var gridStore = gridData.store._arrayOfAllItems;//the store of one grid
    //populates the array with the values for one record
        for (var i=0; i< gridStore.length; i++) {
            rowData.length = 0;
            var gridRec = gridStore;         
            arrayUtil.forEach (fieldNames, function(fieldName) {
            var lastField = fieldNames[fieldNames.length -1];
                fieldValue = gridRec[fieldName];
                var stringValue = String(fieldValue);
                    if (stringValue.indexOf(",") > 0) {
                        console.log ("Field Value before replace " + stringValue);                      
                        stringValue = stringValue.replace(/,/g , " ");
                        console.log ("Field Value after replace = " + stringValue);
                    }
                    if (stringValue.indexOf('\'') != -1 || stringValue.indexOf('\"') != -1 ) {
                    console.log ("Data has a slash in it. Not sure of this section of the code!");
                       if (stringValue.indexOf('\"') != -1) {
                           stringValue = stringValue.replace("\"", "\"\"");
                        }               
                        stringValue = "\"" + stringValue + "\"";
                    }
                    if (fieldName == lastField) {
                    dataArray.push(stringValue + " \n");
                    }else{
                    dataArray.push(stringValue);
                    }
            });
        }//end of one row of datarecord
        }
        var data = dataArray.join();
        var inputData = data.replace(/\n,/g, "\n");//some clean up to get rid of the leading commas in the data
        submitCSVprint(gridName, inputData);//calls the form that is mostly hidden which runs the c# script
    });

}

This is the function where it fails.  I can see that it is populating the values so I have a string to act as a file name, I think it must be failing at f.submit. 

Is that not a valid way to use a form anymore?  I don't typically execute C# scripts, nor do I use forms.  Is there something new or different in the AMD style of form that doesn't work like this anymore?  Maybe additional require statements that aren't obvious?  I do have dijit/form/Form. 
function submitCSVprint(gridName, inputData) {
//opens the data in a hidden form used for printing and allows the user to either open or save the file.
var url = "webservices/csv.ashx";
var f = registry.byId("downloadForm");
f.action = url;
dom.byId("reportinput").value = inputData;
var distType = registry.byId("distTypeSelect").value;
var distNum = registry.byId("txtDistNumber").value;
dom.byId("filename").value = distType+"Dist_"+distNum+"_"+gridName;
f.submit();
}


I am still using the same script as before, csv.ashx.  Here that is again:
<%@ WebHandler Language="C#" Class="csv" %>

using System;
using System.Web;

public class csv : IHttpHandler {

public void ProcessRequest (HttpContext context) {
    String content = "no data";
    String filename = "MyFile";
    if (context.Request["report"] != null)
    {
        try
        {
            content = context.Request["report"].ToString();
        }
        catch
        {
        }
    }
    if (context.Request["filename"] != null)
    {
        try
        {
            filename = context.Request["filename"].ToString() + "_" + DateTime.Now.ToString("MMdyyyy");
        }
        catch
        {
        }
    }

    context.Response.ContentType = "text/csv";
    context.Response.AddHeader("Content-disposition","attachment;filename="+filename+".csv");
    context.Response.Write(content);
}

public bool IsReusable {
    get {
        return false;
    }
}

}
0 Kudos
anthonyzzanthonyzz
New Contributor
I recently happen to read something about the grid data export introduction, including the datagrid export to csv, however it was in C# code. Anyways, I put them here and hope it can be some kinda help.

ExportToCSV exporter = new ExportToCSV(this.ketticGridView1);
string fileName = "C:\\ExportedGridData1.csv";
exporter.RunExport(fileName);
void exporter_CSVFormatCell(object sender, Kettic.WinForms.UI.Export.CSV.CSVFormatCellEventArgs e)
{
    if (e.GridColumnIndex == 1 && e.GridRowInformationType == typeof(GridViewDataRowInformation))
    {
        e.CSVCellElement.Value = "Value for Test";
    }
}
0 Kudos