简体   繁体   中英

How to export MySQL data into a CSV file using JavaScript?

I came across this thread: https://stackoverflow.com/a/38328008/15691137

The script works to some extent, I was able to export the data into a xls file. But, the code has links to a deprecated html version. Also, the exported xls file gives an error when I try to open it which is as follows: 在此处输入图像描述

How can I export the data into a CSV format not xls. Also, how can I fix the error that I am facing? Can someone please help me with this code. Thank you.

Add Export button:

<button  type="button" class="btn btn-warning btn-sm" onClick="tableToExcel('testTable', 'W3C Example Table')"   title="Export to Excel">Export</button></div><br/>

Add id to table:

<table class="table table-bordered table-hover " border="1" id="testTable" >

Add script at below of body:

<script type="text/javascript"> 
    var tableToExcel = (function() {
              var uri = 'data:application/vnd.ms-excel;base64,'
              , template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>'
              , base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) }
              , format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) }
              return function(table, name) {
                if (!table.nodeType) table = document.getElementById(table)
                  var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML}
                window.location.href = uri + base64(format(template, ctx))
              }
            })()</script>

To fix the error, right click the file -> Properties (or select the file and hit Alt+Enter), then check the box named 'Unblock'. That message actually isn't an error. It just warns you that the file may be corrupted.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM