0

So I have been trying to export HTML-tables to excel using javascript in IE. Looks like newer IE-browsers won't allow this (version 11). The different feedback from IE is:

1.

  The webpage cannot be displayed

  Most likely cause:
  •Some content or files on this webpage require a program that you don't have installed.
  1. nothing happens...

  2. when using activeX, it tells me that I do not have the supporting app for this, and suggest me finding it in the app-store...

Here are some of the examples I have tried:

 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, filename) {
        if (!table.nodeType) table = document.getElementById(table)
        var ctx = { worksheet: name || 'Worksheet', table: table.innerHTML }

        document.getElementById("dlink").href = uri + base64(format(template, ctx));
        document.getElementById("dlink").download = filename;
        document.getElementById("dlink").click();

    }
})()

AND:

 <script type="text/javascript">
 var tableToExcel = (function() {
 var uri = 'data:application/vnd.ms-csv;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>

AND

        $(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
        });
    });

AND

 function fnExcelReport()
 {

var tab_text="<table><tr>";
var textRange;
tab = document.getElementById('testTable'); // id of actual table on your page

for(j = 0 ; j < tab.rows.length ; j++) 
{   
    tab_text=tab_text+tab.rows[j].innerHTML;
    tab_text=tab_text+"</tr><tr>";
}

tab_text = tab_text+"</tr></table>";

var txt = document.getElementById('txtArea1').contentWindow;
txt.document.open("txt/html","replace");

txt.document.write(tab_text);
txt.document.close();
txt.focus();
tb = txt.document.execCommand("SaveAs",true,"tablename.xls");
return (tb);
}

Anyone have a solution that works on all browsers + IE (version 7-11)?

TorK
  • 567
  • 2
  • 10
  • 27

1 Answers1

-1
<?php 
error_reporting(E_ERROR);
include("connection.php");

//header to give the order to the browser
header('Content-Type: text/csv');
header('Content-Disposition: attachment;filename=exported-data.csv');
$select_table=mysql_query("select * from table");
$rows = mysql_fetch_assoc($select_table);

if ($rows)
{
getcsv(array_keys($rows));
}
while($rows)
{
getcsv($rows);
$rows = mysql_fetch_assoc($select_table);
}

// get total number of fields present in the database
function getcsv($no_of_field_names)
{
$separate = '';


// do the action for all field names as field name
foreach ($no_of_field_names as $field_name)
{
if (preg_match('/\\r|\\n|,|"/', $field_name))
{
$field_name = '' . str_replace('', $field_name) . '';
}
echo $separate . $field_name;

//sepearte with the comma
$separate = ',';
}

//make new row and line
echo "\r\n";
}
?>