Instantly share code, notes, and snippets.

Embed
What would you like to do?
Export Table Data to CSV using Javascript
Example code for exporting data in a table to a csv file.
<!DOCTYPE>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="author" content="Adila Faruk">
<title>Exporting Data to a CSV File</title>
<style type="text/css">
body{
font-family: sans-serif;
font-weight:300;
padding-top:30px;
color:#666;
}
.container{
text-align:center;
}
a{ color:#1C2045; font-weight:350;}
table{
font-weight:300;
margin:0px auto;
border: 1px solid #1C2045;
padding:5px;
color:#666;
}
th,td{
border-bottom: 1px solid #dddddd;
text-align:center;
margin: 10px;
padding:0 10px;
}
hr{
border:0;
border-top: 1px solid #E7C254;
margin:20px auto;
width:50%;
}
.button{
background-color:#1C2045;
color:#E7C254;
padding:5px 20px;
max-width: 300px;
line-height:1.5em;
text-align:center;
margin:5px auto;
}
.button a{ color:#E7C254;}
.refs{ display:block; margin:auto; text-align:left; max-width:500px; }
.refs .label{ font-size:1.4em;}
.refs > ul{ margin-top:10px; line-height:1.5em;}
</style>
</head>
<body>
<div class='container'>
<div id="dvData">
<table>
<tr>
<th>Column One</th>
<th>Column Two</th>
<th>Column Three</th>
</tr>
<tr>
<td>Row 1 Col 1</td>
<td>Row 1 Col 2</td>
<td>Row 1 Col 3 </td>
</tr>
<tr>
<td>Row 2 Col 1</td>
<td>Row 2 Col 2</td>
<td>Row 2 Col 3</td>
</tr>
<tr>
<td>Row 3 Col 1</td>
<td>Row 3 Col 2</td>
<td>Row 3 Col 3</td>
</tr>
</table>
</div>
<br/>
<div class='button'>
<a href="#" id ="export" role='button'>Click On This Here Link To Export The Table Data into a CSV File
</a>
</div>
<hr/>
<div class='refs'>
<div class='label'>References</div>
<ul>
<li><a href="http://stackoverflow.com/questions/16078544/export-to-csv-using-jquery-and-html" target="_blank">Export to CSV using jQuery and HTML (Stack Overflow)</a>
</li>
<li>
<a href="http://adilapapaya.wordpress.com/2013/11/15/exporting-data-from-a-web-browser-to-a-csv-file-using-javascript/" target="_blank">adilapapaya.wordpress.com</a>
</li>
</ul>
</div>
<hr/>
</div>
<!-- Scripts ----------------------------------------------------------- -->
<script type='text/javascript' src='https://code.jquery.com/jquery-1.11.0.min.js'></script>
<!-- If you want to use jquery 2+: https://code.jquery.com/jquery-2.1.0.min.js -->
<script type='text/javascript'>
$(document).ready(function () {
console.log("HELLO")
function exportTableToCSV($table, filename) {
var $headers = $table.find('tr:has(th)')
,$rows = $table.find('tr:has(td)')
// Temporary delimiter characters unlikely to be typed by keyboard
// This is to avoid accidentally splitting the actual contents
,tmpColDelim = String.fromCharCode(11) // vertical tab character
,tmpRowDelim = String.fromCharCode(0) // null character
// actual delimiter characters for CSV format
,colDelim = '","'
,rowDelim = '"\r\n"';
// Grab text from table into CSV formatted string
var csv = '"';
csv += formatRows($headers.map(grabRow));
csv += rowDelim;
csv += formatRows($rows.map(grabRow)) + '"';
// Data URI
var csvData = 'data:application/csv;charset=utf-8,' + encodeURIComponent(csv);
$(this)
.attr({
'download': filename
,'href': csvData
//,'target' : '_blank' //if you want it to open in a new window
});
//------------------------------------------------------------
// Helper Functions
//------------------------------------------------------------
// Format the output so it has the appropriate delimiters
function formatRows(rows){
return rows.get().join(tmpRowDelim)
.split(tmpRowDelim).join(rowDelim)
.split(tmpColDelim).join(colDelim);
}
// Grab and format a row from the table
function grabRow(i,row){
var $row = $(row);
//for some reason $cols = $row.find('td') || $row.find('th') won't work...
var $cols = $row.find('td');
if(!$cols.length) $cols = $row.find('th');
return $cols.map(grabCol)
.get().join(tmpColDelim);
}
// Grab and format a column from the table
function grabCol(j,col){
var $col = $(col),
$text = $col.text();
return $text.replace('"', '""'); // escape double quotes
}
}
// This must be a hyperlink
$("#export").click(function (event) {
// var outputFile = 'export'
var outputFile = window.prompt("What do you want to name your output file (Note: This won't have any effect on Safari)") || 'export';
outputFile = outputFile.replace('.csv','') + '.csv'
// CSV
exportTableToCSV.apply(this, [$('#dvData>table'), outputFile]);
// IF CSV, don't do event.preventDefault() or return false
// We actually need this to be a typical hyperlink
});
});
</script>
</body>
</html>
@Raverito

This comment has been minimized.

Raverito commented May 28, 2015

thank! works in chrome, but not in internet explorer (my version is ie 11).

@AShakthivel

This comment has been minimized.

AShakthivel commented Jun 19, 2015

Sorry, I tried to execute this code from Internet Explorer 11. Its not working. Can you please make it work in IE 11??? Waiting for your response

@Unhashed

This comment has been minimized.

Unhashed commented Jul 24, 2015

Thank you. This is working well but only for the first page of a table - just the visible view.
Is there a way to tweak this to export the entire table?

@kalebdf

This comment has been minimized.

kalebdf commented Aug 19, 2015

@Raverito, @AShakthivel check out my fork https://gist.github.com/kalebdf/ee7a5e7f44416b2116c0/revisions#diff-eacf331f0ffc35d4b482f1d15a887d3bR135
Do a check for IE window.navigator.msSaveOrOpenBlob and then use the Blob object for IE.

@drrhf

This comment has been minimized.

drrhf commented Sep 16, 2015

Kalebdf,
I used your forked code, and it worked perfectly on my Windows machines with Chrome, IE 11, FireFox and Edge browsers.
Thanks very much.

@mitchmccline

This comment has been minimized.

mitchmccline commented Nov 6, 2015

Thank you!

@raghavendrarao-nyros

This comment has been minimized.

raghavendrarao-nyros commented Nov 20, 2015

Hello every one,
is it possible to use css to generate excel file, like merging cells ,applying border and more
please help using css to generate excel with css

@amjad

This comment has been minimized.

amjad commented Nov 24, 2015

Is it possible to save the file with current timestamp in its name?

@stevelka

This comment has been minimized.

stevelka commented Jan 22, 2016

Hi;
Thanks for the script!

I want to use the script for tables where some cells are inputs of text type

Can some one help to achieve this please ?

Thanks in advance

@stevelka

This comment has been minimized.

stevelka commented Jan 24, 2016

Hi,
Can someone help to modify the script that handle tables where some cells are input text.

Regards

@cent040

This comment has been minimized.

cent040 commented Apr 18, 2016

I want to export table tr,td data and also td> input data as well
Like :

you can i get the input data as well in csv

thanks

@DenoBY

This comment has been minimized.

DenoBY commented May 4, 2016

How to to display Russian letters in CSV?

@ghost

This comment has been minimized.

ghost commented Aug 4, 2016

Hi guys,
i have a question, if someone can help me.

I did a the feature that downloads a csv file with javascript in my application.
It works good till 5000 rows circa, after that when i try to download the file the browser gives me a "Connection Error" .. but actually it isn't a network error because i have already ALL the data before to make the CSV string.

Thanks in advance,

Nico

@DongVan

This comment has been minimized.

DongVan commented Nov 17, 2016

thank! works in chrome, but not in internet explorer (my version is ie 11).

@ghost

This comment has been minimized.

ghost commented May 9, 2017

This is great, thank you!

@jgassie

This comment has been minimized.

jgassie commented Jun 20, 2017

Very nice thank you, for my usage I needed to add the following to grabCol to handle non-breaking spaces:
if($text=="\xa0") { $text = ''; }

@sanchita1992

This comment has been minimized.

sanchita1992 commented Mar 25, 2018

In my case my table contains japanese letter.
How do i write japanese table content to file?

@ricardojlrufino

This comment has been minimized.

ricardojlrufino commented Apr 3, 2018

please update, and add option to show only visible

    function grabRow(i,row){
         
        var $row = $(row);
        //for some reason $cols = $row.find('td') || $row.find('th') won't work...
        var $cols = $row.find('td:visible'); 
        if(!$cols.length) $cols = $row.find('th:visible');  
        return $cols.map(grabCol)
                    .get().join(tmpColDelim);
    }

$row.find('td:visible');
$row.find('th:visible');

@krishnadew06

This comment has been minimized.

krishnadew06 commented Jul 19, 2018

HI,

After downloading csv file in google chrome, on filename seletion it is showing data in preview section only in right pane of window. but after opening the file it is showing only header with NO data. Please help me with this.

@falcon164

This comment has been minimized.

falcon164 commented Aug 21, 2018

works perfectly. thanks...

@mcs187

This comment has been minimized.

mcs187 commented Sep 6, 2018

is there the possibility to save the csv on the server?

@filjoseph1989

This comment has been minimized.

filjoseph1989 commented Oct 12, 2018

I tried to add $("#export").click(); on the end but it isn't downloading. What I supposed to do is when I refresh the page, it should automatically download the file.

I have question also here
https://stackoverflow.com/questions/52773673/trying-to-download-csv-file-using-javascrpt-and-simulate-click-using-click-bu

@mateo2181

This comment has been minimized.

mateo2181 commented Nov 29, 2018

Share my file to export html table to csv using a mixin in Vuejs: https://gist.github.com/mateo2181/2d113284a03abe0dd6c2dc443216f638

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment