Export table content to an Excel file

Asked

Viewed 660 times

1

I wonder if it is possible to create a function in PHP and/or Javascript that allows to export the contents of a table in HTML (table inside a div) straight to an Excel file.

I’m trying to take advantage of a function created from the site of a client of mine, but it didn’t work out 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 you click this button, it goes to 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 function of the URL 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 didn’t work. Any idea?

  • Good question...

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 use the windows file association to open it.

Don’t forget to use the header function before echoing any other information in the file, or use plain html to define these headers

The best thing is 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.

  • Like I used window.open in this case?

  • Window.open would work if the table you want to send is small, because you would need to pass it with window.open("[:root]cadAdmin/testExcel? count_div=" + $('#tableOne'). text() Which has a field size limitation

  • Try to use as similar above, use a form that shows nothing and only serve to send this data

Browser other questions tagged

You are not signed in. Login or sign up in order to post.