Export table contents to an Excel file

1

I would like to know if it is possible to create a function in PHP and / or Javascript that allows exporting the contents of an HTML table (table inside a div) directly into an Excel file.

I'm trying to take advantage of a function created from the site of a client of mine, but it did not work very well. So I think I need to do something new.

I thought of something like this: having a table with id = 'tableOne' and having on my page a button with id = 'testExcel'. When I click this button, it goes into my javascript function:

$('#testExcel').click(function(){
    var conteudo_div = $('#tableOne').text();
    $.ajax({
        async: false,
        cache: false,
        data: ({
            conteudo_div: $('#tableOne').text()
        }),
        url: '[:raiz]cadAdmin/testExcel',
        dataType: 'json',
        success: function(data){
            alert(conteudo_div);
        }
    })
});

And then the testExcel URL function is in a Controller file on my page:

public function testExcel(){
    $nome_arquivo = "Listagem de Investidores";
    header("Content-type: application/vnd.ms-excel");
    header("Content-type: application/force-download");
    header("Content-Disposition: attachment; filename=$nome_arquivo.xls");
    header("Pragma: no-cache");

    $html = $_REQUEST['conteudo_div'];
    echo $html;
} 

Only, for now, it did not work. Any ideas?

    
asked by anonymous 17.07.2015 / 16:17

1 answer

1

Try:

public function testExcel(){
    $nome_arquivo = "Listagem de Investidores";
    header("Content-type: text/txt");
    header("Content-Disposition: attachment; filename=$nome_arquivo.xls");
   header("Pragma: no-cache");

    $html = $_REQUEST['conteudo_div'];
    echo $html;
}

And instead of using an ajax, use a window.open or a form.submit instead, then it will try to open the link as a common file and will use the windows file association to open it.

Do not forget to use the header function before echoing any other information in the file, or use pure html to define these headers

It is best that you use the following:

<form target="_blank" action="[:raiz]cadAdmin/testExcel" id="form_excel">
  <input type="hidden" name="conteudo_div" id="conteudo_div">
</form>

Javascript:

$('#testExcel').click(function(){
    $("#conteudo_div").val($('#tableOne').text());
    $("#form_excel").submit();
});

I do something similar but with vbscript.

    
17.07.2015 / 16:37