Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Export HTML table to csv file on client side

I had a html table on my webpage. I need an export functionality like, the user gets a choice of opening or saving it on his local machine upon button click. As i already had the data in table format ready, it needs to read it and export it on client side itself using browser capabilities with out any plugins (jquery,..). Pure JS would be really appreciated.

HTML Table on my webpage:

<table id="incidents">
<tr>
<td>data1</td>
<td>data1</td>
<td>data1</td>
</tr>
<tr>
<td>data2</td>
<td>data2</td>
<td>data2</td>
</tr>
<tr>
<td>data3</td>
<td>data3</td>
<td>data3</td>
</tr>
</table>

I need to export this table into a csv or excel sheet on the clients machine giving the options of open or save

like image 525
Satish Jonnala Avatar asked Jan 18 '23 12:01

Satish Jonnala


1 Answers

Generate the contents of the CSV file as a string in JavaScript (I assume you're not asking SO to just write this code for you), then encode it as Base64 and generate a data: URI with the MIME type text/csv. Redirect the browser to that URI and it should trigger a download dialog for the user.

like image 187
Jordan Running Avatar answered Jan 29 '23 04:01

Jordan Running