How to Export Data Grid as a CSV file after query tasks?

1268
11
Jump to solution
09-24-2018 11:00 AM
Rocky_
by
Occasional Contributor

Hi all.. i am trying to implement an function by which we can export query task result data grid as a CSV file. 

Is there any widget available for this function. I am using 4.8 arcgis javascript .. any ideas or samples with latest versions..

Thanks..

0 Kudos
1 Solution

Accepted Solutions
deleted-user--MMnVrog9xw_
Occasional Contributor

Sure. One thing I forgot that I forgot is that featureHeaders is not actually an array but a comma delimited string (you can just call the toString() method on the array). Also, featureArray is an array of strings not a 2d array (i'll edit my original response). Anyway, I'll take the example QueryTask from the API reference here and modify it to pass results to my exportData function:

require(["esri/tasks/QueryTask", "esri/tasks/support/Query"], function(QueryTask, Query){
  var citiesLayerUrl = " ... "; // Represents the REST endpoint for a layer of cities.
  var fields = ["cityName", "countryName", "POP"]; // Made up some fields
  var queryTask = new QueryTask({
    url: citiesLayerUrl
  });
  var query = new Query();
  query.returnGeometry = true;
  query.outFields = fields; // Use the array of fields from above
  query.where = "POP > 1000000";  // Return all cities with a population greater than 1 million
  // When resolved, returns features and graphics that satisfy the query.
  queryTask.execute(query).then(function(results){
    console.log(results.features);
    var exportFields = [];
    var exportHeaders = fields.toString();
    var features = results.features;
    for (f in features){
        var row = "";
        for (i in targetLayer.fields){
            row += features[f].attributes[targetLayer.fields[i]]
            if (i !== (targetLayer.fields.length - 1)){
                row += ",";
            }
                            }
            exportFields.push(row);
        }
    exportData(exportFields, exportHeaders);
  });

});‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍

View solution in original post

11 Replies
deleted-user--MMnVrog9xw_
Occasional Contributor

I'm not aware of an out-of-the-box solution but I wrote a function to export results from a query for a web map that I created.

It takes an array of strings ( i.e. ["field1, field2, field3", "field1, field2, field3"]) and an array of field names. It then puts that all into a CSV formatted string and encodes that as a URI and attaches that to a href element.  

function exportData(featureArray, featureHeaders){
    // creates downloadable csv file of selected features

    document.getElementById("status").innerHTML = "Generating Download Link..."
    var csvContent = "data:text/csv;charset=utf-8,";
    csvContent += featureHeaders + "\r\n";
    for (x in featureArray){
        csvContent += featureArray[x] + "\r\n";
    }
    var encodedUri = encodeURI(csvContent);
    // the div where the link will be placed
    var searchDiv = document.getElementById("searchDiv");
    // Get link element or create it if it does not exist yet
    try{
        var link = document.getElementById("downloadLink")

        if (link == null){
            throw "nullException";
        }
    }catch (e){
        var link = document.createElement("a");
    }finally{
        link.setAttribute("href", encodedUri);
        link.setAttribute("download", "data.csv");
        link.setAttribute("id", "downloadLink");
        link.innerHTML= "Download Feature List";
        link.hidden = false;

        document.getElementById("status").innerHTML = "";
        searchDiv.appendChild(link);
    }
};‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍
Rocky_
by
Occasional Contributor

Hello james.. it was really helpful but can you please give me an example by using this function..

0 Kudos
deleted-user--MMnVrog9xw_
Occasional Contributor

Sure. One thing I forgot that I forgot is that featureHeaders is not actually an array but a comma delimited string (you can just call the toString() method on the array). Also, featureArray is an array of strings not a 2d array (i'll edit my original response). Anyway, I'll take the example QueryTask from the API reference here and modify it to pass results to my exportData function:

require(["esri/tasks/QueryTask", "esri/tasks/support/Query"], function(QueryTask, Query){
  var citiesLayerUrl = " ... "; // Represents the REST endpoint for a layer of cities.
  var fields = ["cityName", "countryName", "POP"]; // Made up some fields
  var queryTask = new QueryTask({
    url: citiesLayerUrl
  });
  var query = new Query();
  query.returnGeometry = true;
  query.outFields = fields; // Use the array of fields from above
  query.where = "POP > 1000000";  // Return all cities with a population greater than 1 million
  // When resolved, returns features and graphics that satisfy the query.
  queryTask.execute(query).then(function(results){
    console.log(results.features);
    var exportFields = [];
    var exportHeaders = fields.toString();
    var features = results.features;
    for (f in features){
        var row = "";
        for (i in targetLayer.fields){
            row += features[f].attributes[targetLayer.fields[i]]
            if (i !== (targetLayer.fields.length - 1)){
                row += ",";
            }
                            }
            exportFields.push(row);
        }
    exportData(exportFields, exportHeaders);
  });

});‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍

View solution in original post

Rocky_
by
Occasional Contributor

Hi James..Thanks for the reply. Here we are exporting results to CSV for only one URL and its features.. What can i do if i am having more than 2 featurem URLs with different fields.. How to use your same function..?

0 Kudos
deleted-user--MMnVrog9xw_
Occasional Contributor

That kind of depends on how your code is set up. You could actually move a lot of this code into the exportData function and just have the function accept a featureSet from the query results as well as the list of field names for the headers. 

Rocky_
by
Occasional Contributor

Thank you very much for replying answer to my question. I have to try this again specifically. Really appreciate your suggestions.

 
Best regards

0 Kudos
Rocky_
by
Occasional Contributor

Hi James, I am able to implement function for Exporting Result Grid table as CSV file.. but when am using this function all columns export instead of only selected columns by the user..

Can you please take a look..

function export_table_to_csv() {
var html = document.getElementById("gridTable").innerHTML;
var filename = "QueryResult.csv";
var csv = [];
var rows = document.querySelectorAll("table tr");

for (var i = 0; i < rows.length; i++) {
var row = [], cols = rows.querySelectorAll("td, th");

for (var j = 0; j < cols.length; j++)
row.push(cols.innerText);

csv.push(row.join(","));
}

If you have any questions please feel free to ask.

Thank You

0 Kudos
deleted-user--MMnVrog9xw_
Occasional Contributor

How are you having them select the columns?

0 Kudos
Rocky_
by
Occasional Contributor

Its actually just show/hide function as below... I am using ColumnHider

Grid = new(declare([OnDemandGrid, Selection, ColumnHider]))({
bufferRows: Infinity,
columns: columns
}, "Grid");

By using this function user can just Check/ Uncheck particular columns...

0 Kudos