4

I have created a web application using the esri javascript web api. I populate a dojo datagrid with results returned from a querytask. My question is, how do I export the results to a csv file?

I have been able to loop through the datagrid and add all the results to a csv string, but have not been able to figure out how to actually write it to a document and prompt the user to download the file.

Any help would be greatly appreciated.

Thanks, Mark

4
  • 1
    You can't, for security reasons browsers don't allow file system access. you have to do this serverside an create a download link. (for example with python or php)
    – warrieka
    Aug 5, 2013 at 16:48
  • Thanks for the response. Could you post an example of a python or php script that would accomplish this? I have not used php before and not sure where to even start with this.
    – Mark B
    Aug 5, 2013 at 18:42
  • @warrieka It's true that you can't directly access the filesystem, but you can create a data URI and prompt the user to "download" it: stackoverflow.com/a/14966131/386205
    – blah238
    Aug 6, 2013 at 2:29
  • I never realized something like this could work as well (i should try this some time).
    – warrieka
    Aug 6, 2013 at 8:38

2 Answers 2

3

I am able to accomplish this using a .NET Generic Handler (I got this code from a client project that ESRI consulting abandoned, so this must be how they do it too).

This example is for .NET, but you could do the same thing using other languages.

Here's the code for the handler. Mine is called csv.ashx.

<%@ 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("MMMd_HH.mm.ss");
        }
        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;
    }
}

}

If your code is running in an IIS virtual directory, then include this file in your project.

Next is the JavaScript code. Sounds like you're already storing the csv contents as a string. I use an array called _csvreport to store the contents of the array.

To add entries, I'd do something like:

_csvreport.push("column1,column2,column3");

Then, to start a new row:

_csvreport.push("\r");

That translates to dropping to the next line in your csv. Add more entries and repeat as desired.

When the user clicks a button to create the CSV, call a function like this:

function getCSV() {
//Get the stored CSV
var url = "webservices/csv.ashx";

var data = _csvreport.join("");

var f = dojo.byId("downloadform");
f.action = url;
dojo.byId("reportinput").value = data;
f.submit();
}

This function takes the _csvreport array and makes a string. It then injects that string into a hidden form on your .html page and posts the form.

The code for the form is as follows (and should be hidden from view):

    <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>

I put that just inside of the body of the page that will contain the CSV export functionality.

Probably seems like a lot of work, but it's not that bad once you set it up.

The end result is that when the user clicks the export button, a csv file gets offered up for download.

Notice that the form contains a filename input field, so you could dynamically pass filenames for the handler to use. In this case I just hard coded it in the .ashx file.

The form also contains some other inputs that I'm not using, but that must have been originally used by ESRI. I think they had a format field (pdf vs. csv) and an option to set the number of columns. I just left those in there, but you could probably remove them.

Hope that helps.

1
  • Thanks Ryan, It is working great! I had been trying to figure out for over a month now and you gave by far the most detailed explanation of how to accomplish it. Thanks you very much. - Mark
    – Mark B
    Aug 6, 2013 at 14:07
2

You can use the Enhanced grid and a plugin to do the work on the client side: http://dojotoolkit.org/reference-guide/1.8/dojox/grid/EnhancedGrid/plugins/Exporter.html

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.