Getting Data In
Highlighted

Export to csv on click of button

Engager

Hi everyone. I am just new to splunk and i am trying to create a function where I can export a table results to a csv file using a javascript. can someone tell me what can i do?

Any help will be much appreciated!!

Highlighted

Re: Export to csv on click of button

Legend

Hi riya1,
if you are asking to export a table in a csv from the search form, see in on the top right part of the screen, under the time picker and near the print button: there's a button to export search results.
If instead you are in a dashboard panel in the bottomof the panel, there's a button with a magnifying glass that does the same thing.

Bye.
Giuseppe

0 Karma
Highlighted

Re: Export to csv on click of button

Champion

Hi

Check this sample

<dashboard script="multi.js">
  <label>csv</label>
  <row>
    <panel>
      <html>
        <div id="tableplain"></div>
      </html>
    </panel>
  </row>
  <row>
    <html>
      <button id="export">Export</button>
    </html>
  </row>
</dashboard>

js:

require([
    "jquery",
    "splunkjs/mvc/searchmanager",
    "splunkjs/mvc/tableview",
    "splunkjs/mvc/simplexml/ready!"
], function ($, SearchManager,TableView) {
    $(document).ready(function()
 {
    var search1 = new SearchManager({
        id: "search1",
        preview: true,
        cache: true,
        search: "index=_internal | stats count by sourcetype, source, host" 
    });

    var myplaintable = new TableView({
        managerid: "search1",
        el: $("#tableplain")
    }).render();

    $("#export").click(function(){
        var myResults = search1.data("results");
        myResults.on("data", function () {
             var data = myResults.collection().toJSON();
             console.log(data);
             DownloadJSON2CSV(data);
         });
      });


      function DownloadJSON2CSV(objArray)
      {
        var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
        var str = '';
        var headers = new Array();
        for (var i = 0; i < array.length; i++) {
            var line = '';
            var data = array[i];
            for (var index in data) {
                headers.push(index);
                if (line != '') {
                    line += ','
                }
                line += '"' + array[i][index] + '"';
                console.log('line: ' + line);
            }
            str += line + ((array.length>1) ? '\r\n' : '');
            line = '';
        }

        headers = getHeaders(headers);
        str = headers + '\r\n' + str;
        console.log('final : ' + str);
        var hiddenElement = document.createElement('a');
        hiddenElement.href = 'data:text/csv;charset=utf-8,' + encodeURI(str);
        hiddenElement.target = '_blank';
        hiddenElement.download ='download.csv';
        hiddenElement.click();
    }

    function getHeaders(a) {
        var temp = {};
        for (var i = 0; i < a.length; i++)
            temp[a[i]] = true;
        var r = [];
        for (var k in temp)
            r.push(k);
        return r;
    }

});
});

alt text

View solution in original post

Highlighted

Re: Export to csv on click of button

Contributor

the code works however if the data on the table is not yet populated, you will get infinite number of export file until the data are completed. that's the time that the export file will stop and will give a final export file.

0 Karma
Highlighted

Re: Export to csv on click of button

Champion

Hi

Try this, the Export button will get enable after the data loaded completely in the table.

<dashboard script="multi.js">
  <label>csv</label>
  <row>
    <panel>
      <html>
         <div id="tableplain"/>
       </html>
    </panel>
  </row>
  <row>
    <html>
       <button id="export" disabled="true">Export</button>
     </html>
  </row>
</dashboard>

js:

require([
    "jquery",
    'splunkjs/mvc',
    "splunkjs/mvc/searchmanager",
    "splunkjs/mvc/tableview",
    "splunkjs/mvc/simplexml/ready!"
], function ($,mvc, SearchManager,TableView) {
    $(document).ready(function()
 {
    var tokens = mvc.Components.get("default");

    var search1 = new SearchManager({
        id: "search1",
        preview: true,
        cache: true,
        search: "index=_internal | stats count by sourcetype, source, host" 
    });

    search1.on('search:done', function() {
        $('#export').prop('disabled', false);
     });

    var myplaintable = new TableView({
        managerid: "search1",
        el: $("#tableplain")
    }).render();

    $("#export").click(function(){
        var myResults = search1.data("results");
        myResults.on("data", function () {
             var data = myResults.collection().toJSON();
             console.log(data);
             DownloadJSON2CSV(data);
         });

      });


      function DownloadJSON2CSV(objArray)
      {
        var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
        var str = '';
        var headers = new Array();
        for (var i = 0; i < array.length; i++) {
            var line = '';
            var data = array[i];
            for (var index in data) {
                headers.push(index);
                if (line != '') {
                    line += ','
                }
                line += '"' + array[i][index] + '"';
                console.log('line: ' + line);
            }
            str += line + ((array.length>1) ? '\r\n' : '');
            line = '';
        }

        headers = getHeaders(headers);
        str = headers + '\r\n' + str;
        console.log('final : ' + str);
        var hiddenElement = document.createElement('a');
        hiddenElement.href = 'data:text/csv;charset=utf-8,' + encodeURI(str);
        hiddenElement.target = '_blank';
        hiddenElement.download ='download.csv';
        hiddenElement.click();
    }

    function getHeaders(a) {
        var temp = {};
        for (var i = 0; i < a.length; i++)
            temp[a[i]] = true;
        var r = [];
        for (var k in temp)
            r.push(k);
        return r;
    }

});
});
Highlighted

Re: Export to csv on click of button

Contributor

Hello Vnravikumar, thanks for this.. hmm, do you happen to encounter to export without max lines? becausse this one limits to 100 results only

Highlighted

Re: Export to csv on click of button

Champion

Hi

replace this line in js

var myResults = search1.data("results",{count: 0, output_mode: 'json_rows'});
Highlighted

Re: Export to csv on click of button

Contributor

thanks for all the help for the csv.. is there a way to implement this also in export xls?

Highlighted

Re: Export to csv on click of button

Loves-to-Learn Lots

Hi @vnravikumar 

Thank you for giving this code.

We are also working on this same future But when you click on export button it is giving more number of csv files instead of 1 (more than 5)

I tried the same code in search done as well .

Can you please help us to resolve this issue .

Thanks & Regards,

Manikanth

0 Karma
Highlighted

Re: Export to csv on click of button

Engager

This worked! Thanks!

0 Karma