cssAudio - Activefile-genericCSS - ActiveGeneric - ActiveHTML - ActiveImage - ActiveJS - ActiveSVG - ActiveText - Activefile-genericVideo - ActiveLovehtmlicon-new-collectionicon-personicon-teamlog-outoctocatpop-outspinnerstartv

Pen Settings

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Code Indentation

     

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

            
              <script src='https://code.jquery.com/jquery-2.2.4.min.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.min.js'></script>
<script src='https://public.tableau.com/javascripts/api/tableau-2.js'></script>
<script src='https://cdn.jsdelivr.net/alasql/0.3/alasql.min.js'></script>

<body>

  <div class="select-style"><select id="SheetList"></select></div>
  <button class="button" onclick="getVizData()">Export data to CSV file</button>
  <div id="vizDiv"></div>

</body>
            
          
!
            
              .button {
  background-color: #00aeef;
  /* Green */
  border: none;
  color: white;
  padding: 5px 8px;
  border: 1px solid #fff;
  width: 200px;
  top: 50%;
  left: 50%;
  border-radius: 3px;
  font-family: "Trebuchet MS", Helvetica, sans-serif;
  text-decoration: none;
  display: inline-block;
  font-size: 14px;
  cursor: pointer;
  cursor: hand;
}

.select-style {
  padding: 0;
  margin: 0;
  border: 1px solid #00aeef;
  font-family: "Trebuchet MS", Helvetica, sans-serif;
  width: 200px;
  border-radius: 3px;
  overflow: hidden;
  background-color: #fff;
  background: #fff url("http://www.scottgood.com/jsg/blog.nsf/images/arrowdown.gif") no-repeat 90% 50%;
}

.select-style select {
  padding: 5px 8px;
  width: 130%;
  border: none;
  box-shadow: none;
  font-family: "Trebuchet MS", Helvetica, sans-serif;
  background-color: transparent;
  background-image: none;
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;
}

.select-style select:focus {
  outline: none;
}
            
          
!
            
              //first, create the viz
$(document).ready(function initViz() {

  var vizDiv = document.getElementById("vizDiv"),
    url = "https://public.tableau.com/views/getData_Demo/getData_Demo?:embed=y&:display_count=yes",

    options = {

      hideToolbar: true,
      onFirstInteractive: function() {

        workbook = viz.getWorkbook();
        dash = viz.getWorkbook().getActiveSheet();
        workbook.activateSheetAsync(dash)
          .then(function(dashboard) {
            //this is the secret sauce that stores all of the sheet names on the dashboard in an array named sheetNames
            var worksheets = dashboard.getWorksheets();
            //here is the aforementioned array
            var sheetNames = [];
            //here we are looping through all the sheets on the dash, & pushing the sheet name to the sheetNames array
            for (var i = 0, len = worksheets.length; i < len; i++) {

              var sheet = worksheets[i];
              sheetNames.push(sheet.getName());
            }

            //here is where we are creating our dropdown menu... kind of like a Tableau parameter
            //we will inject this value into the getVizData() function a little bit later
            var sel = document.getElementById('SheetList');
            var fragment = document.createDocumentFragment();
            sheetNames.forEach(function(sheetName, index) {

              var opt = document.createElement('option');
              opt.innerHTML = sheetName;
              opt.value = sheetName;
              fragment.appendChild(opt);
            });

            sel.appendChild(fragment);

          });
      }
    };
  viz = new tableau.Viz(vizDiv, url, options);
});

//if you've made it to this point, know that the magic came from here: https://www.interworks.com/blog/rrouse/2016/06/07/pull-viz-data-new-javascript-api-features-tableau-10
function getVizData() {
  options = {

    maxRows: 0, // Max rows to return. Use 0 to return all rows
    ignoreAliases: false,
    ignoreSelection: true,
    includeAllColumns: false
  };

  sheet = viz.getWorkbook().getActiveSheet();

  //if active tab is a worksheet, get data from that sheet
  if (sheet.getSheetType() === 'worksheet') {
    sheet.getUnderlyingDataAsync(options).then(function(t) {
      buildMenu(t);
    });

    //if active sheet is a dashboard get data from a specified sheet
  } else {
    worksheetArray = viz.getWorkbook().getActiveSheet().getWorksheets();
    for (var i = 0; i < worksheetArray.length; i++) {
      worksheet = worksheetArray[i];
      sheetName = worksheet.getName();

      //get user's selection from dropdown of sheets
      var selectedVal = document.getElementById("SheetList").value;

      //get the data from the selected sheet
      if (sheetName == selectedVal) {
        worksheetArray[i].getSummaryDataAsync(options).then(function(t) {
          buildMenu(t);
        });
      }
    }
  }
}

//restructure the data and build something with it
function buildMenu(table) {

  //the data returned from the tableau API
  var columns = table.getColumns();
  var data = table.getData();

  //convert to field:values convention
  function reduceToObjects(cols, data) {
    var fieldNameMap = $.map(cols, function(col) {
      return col.$impl.$fieldName;
    });
    var dataToReturn = $.map(data, function(d) {
      return d.reduce(function(memo, value, idx) {
        memo[fieldNameMap[idx]] = value.value;
        return memo;
      }, {});
    });
    return dataToReturn;
  }

  var niceData = reduceToObjects(columns, data);

  //take the niceData and send it to a csv named TableauDataExport
  alasql("SELECT * INTO CSV('TableauDataExport.csv',{headers:true}) FROM ?", [niceData]);

}
            
          
!
999px
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.
Loading ..................

Console