MediaWiki:Gadget-table-csv.js

After saving, you may need to bypass your browser's cache to see the changes. For further information, see Wikipedia:Bypass your cache.

  • In most Windows and Linux browsers: Hold down Ctrl and press F5.
  • In Safari: Hold down ⇧ Shift and click the Reload button.
  • In Chrome and Firefox for Mac: Hold down both ⌘ Cmd+⇧ Shift and press R.
$(function () {
	function cellToString(cell) {
		var $cell = $(cell).clone();
		$cell.find('a').replaceWith(function(){
			var $e = $(this);
			if ($e.text() === '') { //the handles normal linked images
				return $e.attr('title');
			}
			return $e.text();
		});
		$cell.find('img').replaceWith(function(){ //any extra images without a link
			return $(this).attr('alt')
		})
		return '"\''+$cell.text().trim()+'"';
	}
	
	function sanitisePagename() {
		var pn = mw.config.get('wgPageName');
		pn = pn.replaceAll(/[\/\\:?*<>"|]/gi, '-');
		return pn;
	}

	function downloadTableCSV(event) {
		var $targ = $(event.currentTarget);
		var $table = $targ.parents('table.wikitable').first();
		var data = [];
		var rowspans = [];
		// set up rowspans array
		$table.find('>tr, >*>tr').first().find('>th,>td').each(function(i,e) {
			// account for colspan in headers
			// we are assuming all rows have the same number of columns
			var cspan = $(e).attr('colspan');
			cspan = parseInt(cspan)
			if (cspan === NaN) {
				cspan = 1;
			}
			for (var j=1; j<cspan; j++) {
				rowspans.push(0);
			}
		});
		
		$table.find('>tr, >*>tr').each(function(i,e){
			var row = [];
			var i_real = 0;
			$(e).find('td,th').each(function(i2,e2){
				while (true) {
					while (i_real >= rowspans.length) {
						rowspans.push(0);
					}
					if (rowspans[i_real] > 1) {
						rowspans[i_real]--;
						i_real++;
						row.push('""');
					} else {
						break;
					}
				}
				row.push(cellToString(e2));
			 	var cspan = $(e2).attr('colspan');
				cspan = parseInt(cspan);
				if (cspan !== NaN) {
					for (var i = 1; i < cspan; i++) {
						row.push('""');
					}
				}
				var rspan = $(e2).attr('rowspan');
				rspan = parseInt(rspan);
				if (rspan === NaN) {
					rspan = 1;
				}
				rowspans[i_real] = rspan;
				i_real++;
			});
			data.push(row.join(','));
		});
		var b = new Blob([data.join('\n')], {type:'text/csv'});
		$table.find('a.rsw-gadget-csv-download').attr({
			href: window.URL.createObjectURL(b),
			download: sanitisePagename()+'.table'+$table.attr('data-rsw-csv-num')+'.csv'
		});
	}
	
	 function init() {
		var $tables = $('#mw-content-text .mw-parser-output table.wikitable:not(.infobox)');
		if ($tables.length===0) {
			return;
		}
		$tables.each(function(i,e){
			$(e).attr('data-rsw-csv-num', i).append(
				$('<caption>').append(
					$('<a>').text('Download CSV').addClass('rsw-gadget-csv-download')
				).attr('title', 'Download this table as a CSV')
			);
		});
		$tables.find('a.rsw-gadget-csv-download').on('click', downloadTableCSV);
	}
	init()
})