简体   繁体   English

仅将选定的行导出到 Laravel 中的 csv

[英]Export only selected rows into csv in Laravel

I have to export only the selected rows using checkbox into csv here is my code.我必须使用复选框仅将选定的行导出到 csv 这是我的代码。 I am using ajax to pass multiple user id to the controller but I don't know how to export only passing user ids please help the problem is, it is just returning an empty excel file我正在使用 ajax 将多个用户 ID 传递给 controller 但我不知道如何仅导出传递的用户 ID 请帮助解决问题,它只是返回一个空的 ZBF57C906FA7D2BB656D07372E46Z1

在此处输入图像描述

Export Csv button出口Csv按钮

<a data-href="/admin/export/selected/data" class="btn btn-filter btn-secondary" id="export_records">Export
            Selected</a>

在此处输入图像描述

Ajax code for multiple select Ajax 代码为多个 select

    <script>
    $(document).on('click', '#selectAll', function() {

        $(".user_checkbox").prop("checked", this.checked);
        $("#select_count").html($("input.user_checkbox:checked").length + " Selected");
    });
    $(document).on('click', '.user_checkbox', function() {

        if ($('.user_checkbox:checked').length == $('.user_checkbox').length) {
            $('#selectAll').prop('checked', true);
        } else {
            $('#selectAll').prop('checked', false);
        }
        $("#select_count").html($("input.user_checkbox:checked").length + " Selected");
    });
    $(document).ready(function() {
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });

        $('#export_records').on('click', function(e) {
            var user = [];
            $(".user_checkbox:checked").each(function() {
                user.push($(this).data('user-id'));
            });
            if (user.length <= 0) {
                alert("Please select records.");
            } else {


                var selected_values = user;
                $.ajax({
                    type: "get",
                    url: "{{ route('export.csv') }}",
                    cache: false,
                    data: 'user_id=' + selected_values,
                    success: function(response) {

                        let _url = $("#export_records").data('href');
                        window.location.href = _url;
                    }
                });
            }

        });

    });

</script>

Controller to download csv Controller 下载 csv

 public function exportCsv(Request $request)
{
    $users = User::whereIn('id', explode(",", $request->user_id))->get();
    $filename = "UsersData.csv";
    $headers = array(
        'Content-Type' => 'text/csv',
        "Content-Disposition" => "attachment; filename=$filename",
        "Pragma"              => "no-cache",
        "Cache-Control"       => "must-revalidate, post-check=0, pre-check=0",
        "Expires"             => "0"
    );
    $callback = function() use($filename, $users) {
    $handle = fopen('php://output', 'w');
    fputcsv($handle, array('name','email', 'company_name','role', 'created_at'));

    foreach ($users as $user) {
            $row['name']  = $user->name;
            $row['email']    = $user->email;
            $row['company_name']    = $user->company_name;
            $row['role']  = $user->roles->name;
            $row['created_at']  = $user->created_at;
        fputcsv($handle, array($row['name'], $row['email'], $row['company_name'], $row['role'], $row['created_at']->format('l jS \of F Y')));
    }

    fclose($handle);
};
    

    return Response::stream($callback, 200, $headers);
}

Note this code is working for all user data export in csv like $users = User::all() but not working with selected ones请注意,此代码适用于 csv 中的所有用户数据导出,例如$users = User::all()但不适用于选定的

ajax response ajax响应

在此处输入图像描述

Try to send data like尝试发送数据,如

data: {user_id: selected_values}

instead of,代替,

data: 'user_id=' + selected_values,

and then in the backend you don't need to use explode, you will directly get array of user ids.然后在后端你不需要使用explode,你会直接得到用户ID数组。

hopefully, I got the solution I was just missing the URL with window.location.href I also had to pass user_id with it.希望我得到了解决方案,我只是错过了 URL 和window.location.href我还必须传递 user_id 。 so here is the modified part,所以这里是修改的部分,

$.ajax({
      type: "GET",
       url: "{{ route('exportOption.Userscsv') }}",
       cache: false,
       data: 'user_id=' + selected_values,
       success: function(response) {
          let _url = $("#export_records").data('href');
          var selected_values = user;
          window.location.href = _url + '?user_id=' + selected_values;

                    }
           });

Hope it will be helpful for you guys.希望对大家有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM