首页 > php > 将数据库查询结果转换为excel并允许从ajax调用下载

将数据库查询结果转换为excel并允许从ajax调用下载 (Convert database query results to excel and allow download from ajax call)

2018-08-03 phpjqueryajax

问题

我已经查看了一些类似的问题但是找不到我要找的东西(请不要将其标记为重复,因为我试图找到答案而不发布问题)

当用户单击按钮时,会向控制器发送ajax请求,我将从模型中获取数据。然后我将其转换为csv格式,并且在ajax调用成功后我想要下载该文件。我有一切工作,除了下载部分。我看过一些例子,你只是重定向,但没有下载任何东西,它显示了一个包含结果的新页面。

$( '.spExcel' ).on('click', function() {
    $.ajax({
        url: url + '/Widgets/exportSpExcel',
        type: 'POST',
    })

    .done(function (data) {
        window.location.assign(data);

    })
});

PHP:

    if($_SERVER['REQUEST_METHOD'] === 'POST') {


        $results = $this->DashboardModel->listPeople();
        $filename = 'People_' . date('dmY') . '.csv'; 

        header("Content-Description: File Transfer");
        header("Content-Type: application/csv");
        header("Content-Disposition: attachment; filename=$filename");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");

        $handle = fopen('php://output', 'w');

        $header = array("Name", "Contact Number"); 
        fputcsv($handle, $header);      

        foreach ($results as $result):
            fputcsv($handle, $result);
        endforeach;

        fclose($handle);

    }

解决方法

Ajax无法编写下载的文件 - 浏览器必须自己编写。您可以使用,window.open()但这会在新的选项卡或窗口中打开文件,然后立即关闭。这可能看起来很乱 - 它起作用但不理想。

处理此问题的最简单方法是使链接直接下载响应,而不尝试使用Ajax。更改链接以满足您的需求,但它会是这样的......

<a href="/Widgets/exportSpExcel" class="spExcel" download>click to download</a>

只需将download属性添加到链接即可。它真的很简单:)

问题

I have looked through a few similar questions but can't quite find what I am looking for (please don't mark this as duplicate as I did try to find an answer without posting a question)

When the user clicks on a button, an ajax request is sent to the controller where I am getting data back from the model. I am then converting it to a csv format and on success of the ajax call I want the file to download. I have everything working except the download part. I have seen some examples where you just redirect but that doesn't download anything, it shows a new page with the results.

$( '.spExcel' ).on('click', function() {
    $.ajax({
        url: url + '/Widgets/exportSpExcel',
        type: 'POST',
    })

    .done(function (data) {
        window.location.assign(data);

    })
});

PHP:

    if($_SERVER['REQUEST_METHOD'] === 'POST') {


        $results = $this->DashboardModel->listPeople();
        $filename = 'People_' . date('dmY') . '.csv'; 

        header("Content-Description: File Transfer");
        header("Content-Type: application/csv");
        header("Content-Disposition: attachment; filename=$filename");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");

        $handle = fopen('php://output', 'w');

        $header = array("Name", "Contact Number"); 
        fputcsv($handle, $header);      

        foreach ($results as $result):
            fputcsv($handle, $result);
        endforeach;

        fclose($handle);

    }

解决方法

Ajax isn't capable of writing a downloaded file - the browser has to do that itself. You could use window.open() but that would open the file in a new tab or window, which would then close immediately. That can look messy - it works but isn't ideal.

The simplest way to deal with this is to make the link download the response directly, without trying to use Ajax. Change the link to suit your needs, but it would be something like this...

<a href="/Widgets/exportSpExcel" class="spExcel" download>click to download</a>

Just add the download attribute to a link. It really is that simple :)

相似信息