Export to CSV using jQuery and html -


i have tabular data need export csv without using external plugin or api. used window.open method passing mime types faced issues below:

how determine whether microsoft excel or open office installed on system using jquery

the code should independent of fact being installed on system i.e., openoffice or ms excel. believe csv format can expected show in both editors.

code

    <html>  <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>    <script type="text/javascript"> $(document).ready(function(){     $("#btnexport").click(function(e) {         var msg = getmimetypes();         //openoffice         window.open('data:application/vnd.oasis.opendocument.spreadsheet,' + $('#dvdata').html());         //ms-excel         window.open('data:application/vnd.ms-excel,' + $('#dvdata').html());         //csv         window.open('data:application/csv,charset=utf-8,' + $('#dvdata').html());         e.preventdefault();     }); });  function getmimetypes () {     var message = "";         // internet explorer supports mimetypes collection, empty     if (navigator.mimetypes && navigator.mimetypes.length > 0) {         var mimes = navigator.mimetypes;         (var i=0; < mimes.length; i++) {             message += "<b>" + mimes[i].type + "</b> : " + mimes[i].description + "<br />";         }     }     else {         message = "your browser not support ";        //sorry!     }      return ( message); } </script>  </head> <body> <div id="dvdata"> <table>     <tr>         <th>column 1 </th>         <th>column two</th>         <th>column three</th>     </tr>     <tr>         <td>row1 col1</td>         <td>row1 col2</td>         <td>row1 col3</td>    </tr>    <tr>         <td>row2 col1</td>         <td>row2 col2</td>         <td>row2 col3</td>    </tr>       <tr>         <td>row3 col1</td>         <td>row3 col2</td>         <td>row3 col3</td>      </tr> </table> </div> <br/> <input type="button" id="btnexport" value=" export table data excel " />  </body> 

errors:

csv: unrecognised on browsers

ods & excel: working not able find 1 generate when system having excel installed or openoffice installed?

ie version 8 : totally not working, opens in new window , below screenshot.

enter image description here

here's demo first, explanations afterwards:

$(document).ready(function() {      function exporttabletocsv($table, filename) {        var $rows = $table.find('tr:has(td)'),          // temporary delimiter characters unlikely typed keyboard        // avoid accidentally splitting actual contents        tmpcoldelim = string.fromcharcode(11), // vertical tab character        tmprowdelim = string.fromcharcode(0), // null character          // actual delimiter characters csv format        coldelim = '","',        rowdelim = '"\r\n"',          // grab text table csv formatted string        csv = '"' + $rows.map(function(i, row) {          var $row = $(row),            $cols = $row.find('td');            return $cols.map(function(j, col) {            var $col = $(col),              text = $col.text();              return text.replace(/"/g, '""'); // escape double quotes            }).get().join(tmpcoldelim);          }).get().join(tmprowdelim)        .split(tmprowdelim).join(rowdelim)        .split(tmpcoldelim).join(coldelim) + '"';        // deliberate 'false', see comment below      if (false && window.navigator.mssaveblob) {          var blob = new blob([decodeuricomponent(csv)], {          type: 'text/csv;charset=utf8'        });          // crashes in ie 10, ie 11 , microsoft edge        // see ms edge issue #10396033        // hence, deliberate 'false'        // here completeness        // remove 'false' @ own risk        window.navigator.mssaveblob(blob, filename);        } else if (window.blob && window.url) {        // html5 blob                var blob = new blob([csv], {          type: 'text/csv;charset=utf-8'        });        var csvurl = url.createobjecturl(blob);          $(this)          .attr({            'download': filename,            'href': csvurl          });      } else {        // data uri        var csvdata = 'data:application/csv;charset=utf-8,' + encodeuricomponent(csv);          $(this)          .attr({            'download': filename,            'href': csvdata,            'target': '_blank'          });      }    }      // must hyperlink    $(".export").on('click', function(event) {      // csv      var args = [$('#dvdata>table'), 'export.csv'];        exporttabletocsv.apply(this, args);        // if csv, don't event.preventdefault() or return false      // need typical hyperlink    });  });
a.export,  a.export:visited {    display: inline-block;    text-decoration: none;    color: #000;    background-color: #ddd;    border: 1px solid #ccc;    padding: 8px;  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>  <a href="#" class="export">export table data excel</a>  <div id="dvdata">    <table>      <tr>        <th>column one</th>        <th>column two</th>        <th>column three</th>      </tr>      <tr>        <td>row1 col1</td>        <td>row1 col2</td>        <td>row1 col3</td>      </tr>      <tr>        <td>row2 col1</td>        <td>row2 col2</td>        <td>row2 col3</td>      </tr>      <tr>        <td>row3 col1</td>        <td>row3 col2</td>        <td>row3 col3</td>      </tr>      <tr>        <td>row4 'col1'</td>        <td>row4 'col2'</td>        <td>row4 'col3'</td>      </tr>      <tr>        <td>row5 &quot;col1&quot;</td>        <td>row5 &quot;col2&quot;</td>        <td>row5 &quot;col3&quot;</td>      </tr>      <tr>        <td>row6 "col1"</td>        <td>row6 "col2"</td>        <td>row6 "col3"</td>      </tr>    </table>  </div>


updates since 2017

added use of html5 blob , url preferred method, , use of data uri fallback.


i see other answers suggesting window.navigator.mssaveblob

however, still reluctant update code add support it, because crashes in ie10 on window 7 , ie11 on windows 10 (for me @ least). worked in microsoft edge though (but ironically crashed user: microsoft edge issue ticket #10396033).

the simple act of calling in microsoft's own developer tools / console causes browser crash.

navigator.mssaveblob(new blob(["hello"], {type: "text/plain"}), "test.txt"); 


it's been 4 years since first answer, 3 versions came out (ie10, 11, edge), , microsoft manages have of them crash on function invented (slow claps)

so, not including in solution.

but adding warning though: add navigator.mssaveblob support @ own risk.


answer since 2013

i curious why cannot implement server-side solution this. there reason?

but fun of it, here attempt on client-side solution.

just dumping html data uri not work in case. need first convert table contents valid csv formatted string. (this easier part.)

but after that, next challenge how download it. reason not window.open approach work in firefox. instead used different approach: <a href="{data uri here}">

with <a> tag, have option assign default file name using download attribute, feasible in firefox , google chrome. since attribute, degrades gracefully.


notes

tests

browsers i've tested include:

  • firefox 20+, win/mac (works)
  • google chrome 26+, win/mac (works)
  • safari 6, mac (filename issue unresolved no javascript errors produced, file contents intact)
  • ie 9+ (fails design, need more)

Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -