使用php ajax调用将mysql数据导出为ex​​cel

时间:2018-04-18 09:16:30

标签: php jquery ajax

我正在进行ajax调用并调用一个php页面,该页面从mysql表中提取数据,需要将其转换为excel并且只需要存储在服务器文件夹中。

现在的问题是在进行ajax调用时,它会进入那个php页面并返回主页而不创建excel文件。

但是当我直接测试php页面时,它会创建excel文件并下载它。但是为什么它不能通过ajax调用。

这是我上一页的ajax调用 -

$.ajax({
    type: "POST",
    url: "admin-advertiser-details-exports.php?selectedColumns="+selectedColumns+"&excelColumn="+excelColumn,
    contentType:false,  
    processData:false,  
    success:function(data){  
        alert('Export done');  
    }
});

这是我的php页面,它导出到excel -

<?php
    session_start();
    include 'db.php';

    if(!isset($_SESSION))
    {
        $uname=$_SESSION['uname'];
    }
    else if(empty($_SESSION['uname']))
    {
        header('Location: index.php',TRUE);
    }

    $UserName = $_SESSION['uname'];
    $UserID = $_SESSION['uid'];
    $UserType = $_SESSION['utype'];

    $selectedColumns = $_GET['selectedColumns'];
    $excelColumn = $_GET['excelColumn'];

    $array = explode('\t',$excelColumn);

    $sql = "select ".$selectedColumns." from advertisers_details ad join user_details ud on ad.adv_manager=ud.user_id order by ad.adv_id asc";

    $setRec = mysqli_query($linkID1, $sql);
    $columnHeader = '';

    foreach ($array as $value) {
        $value = '"' . $value . '"' . "\t";
        $columnHeader .= $value;
    }

    $setData = '';

    while ($rec = mysqli_fetch_row($setRec)) 
    { 
        $rowData = ''; 

        foreach ($rec as $value) 
        { 
            $value = '"' . $value . '"' . "\t"; 
            $rowData .= $value; 
        }

        $setData .= trim($rowData) . "\n"; 
    }

    header("Content-type: application/octet-stream"); 
    header("Content-Disposition: attachment; filename=advertiser_detail.xls"); 
    header("Pragma: no-cache"); 
    header("Expires: 0"); 
    echo ucwords($columnHeader) . "\n" . $setData . "\n";
?>

如果我直接运行这个php页面,我将获得excel文件,但是通过ajax调用它无法正常工作。

1 个答案:

答案 0 :(得分:3)

希望此示例最适合您。 我已经使用window.open并使用参数设置了目标文件的url。

使用了JS代码

/* Export Orders */
$(document).on('click','#btn_export_delivery_order',function(){       
        var first_input = $('#name_email_order_search').val();
        var date_range = $('#reportrangeorder').val();        
        var order_status = $('#order_status').val();                
        window.open("ajax_responce.php?method_name=export_orders&shop="+ shop+"&first_input=" + first_input + "&date_range=" + date_range + "&order_status=" + order_status + "", '_blank');
});

ajax_response.php中使用的代码

公共函数export_orders(){             ob_start();

        if (isset($_GET['shop']) && $_GET['shop'] != '') {
            $export = array();
            $export_data = array();
            $shopinfo = $this->get_settings($_GET['shop']);
            $store_client_id = $shopinfo['store_client_id'];
            $date_format = $shopinfo['date_format_first'];

            $options_arr = array("skip" => 0, "limit" => 99999);            
            $where = $this->where_to_clause_export_search($store_client_id, $_GET);
            $fullfilment_status_array = array('Unfulfilled','Fullfill','Partially fullfill','Cancelled');

            $export_result = $this->select_result(TABLE_ORDERS, '*', $where, $options_arr);

            foreach($export_result['data'] as $row){
                    $export['Name'] = $row['order_name'];
                    $export['Billing Name'] = $row['first_name'] . ' ' . $row['last_name'];
                    $export['Email'] = $row['email'];
                    $export['Fulfillment Status'] = $fullfilment_status_array[$row['status']];
                    $export['Total'] = $row['total'];
                    $export['Created at'] = date($date_format, strtotime($row['created_at']));
                    $export['Delivery Status'] = $row['delivery_status'] == 0 ? 'Pending' : 'Delivered';
                    $export['Delivery Date'] = date($date_format, strtotime($row['delivery_date']));
                    $export['Delivery Time'] = (isset($row['delivery_time']) && $row['delivery_time'] != '') ? $row['delivery_time'] : '-';
                    $export_data[] = $export;
            }

            /* Export Data */
            $filename = "orders_export.csv";
            $f = fopen('php://output', 'w');
            header('Content-type: application/csv');
            header('Content-Disposition: attachment; filename=' . $filename);
            $outputdata = $export_data;

            $firstLineKeys = false;
            foreach ($outputdata as $row) {
                if (empty($firstLineKeys)) {
                    $firstLineKeys = array_keys($row);
                    fputcsv($f, $firstLineKeys);
                    $firstLineKeys = array_flip($firstLineKeys);
                }
                fputcsv($f, $row);
            }
            fclose($f);
            ob_end_flush();
            exit();
        }
    }

此代码已经过测试,可以正常工作。