Xuất dữ liệu với FastAdmin

Thêm vào index.html:

<a href="javascript:;" class="btn btn-primary btn-export {:$auth->check('user/export')?'':'hide'}" title="{:__('Export')}" id="btn-export-file"><i class="fa fa-upload"></i> {:__('Export Data')}</a>

Lưu ý thay đổi đường dẫn tải lên phù hợp.

Thêm vào index.js:

$(document).on("click", ".btn-export", function () {
    const selectedIds = Table.api.selectedids(table);
    const currentPageData = table.bootstrapTable('getData');
    const totalRecords = table.bootstrapTable('getOptions').totalRows;

    console.log(selectedIds.length, currentPageData.length, totalRecords);

    Layer.confirm(
        `<form action="${Fast.api.fixurl("user/export")}" method="post" id="exportForm" target="_blank">
            <input type="hidden" name="selectedIds" id="selectedIdsInput" value="" />
            <input type="hidden" name="filter" />
            <input type="hidden" name="op" />
            <input type="hidden" name="search" />
            <input type="hidden" name="columns" />
        </form>`,
        {
            title: "Xuất dữ liệu",
            btn: [
                `Các mục đã chọn (${selectedIds.length} items)`, 
                `Trang hiện tại (${currentPageData.length} items)`, 
                `Tất cả (${totalRecords} items)`
            ],
            success(layero, index) {
                $(".layui-layer-btn a", layero).addClass("layui-layer-btn0");
            },
            yes(index, layero) {
                if (selectedIds.length > 0) {
                    const form = document.getElementById("exportForm");
                    const inputField = document.getElementById("selectedIdsInput");
                    inputField.setAttribute("value", selectedIds.join(","));
                    form.submit();
                    return true;
                }
                return false;
            },
            btn2(index, layero) {
                const idsOnPage = [];
                $.each(currentPageData, (i, record) => {
                    idsOnPage.push(record.id);
                });
                if (idsOnPage.length > 0) {
                    const form = document.getElementById("exportForm");
                    const inputField = document.getElementById("selectedIdsInput");
                    inputField.setAttribute("value", idsOnPage.join(","));
                    form.submit();
                    return true;
                }
                return false;
            },
            btn3(index, layero) {
                const form = document.getElementById("exportForm");
                const inputField = document.getElementById("selectedIdsInput");
                inputField.setAttribute("value", "all");
                form.submit();
                return true;
            }
        }
    );
});

Cài đặt thư viện PHPExcel:

composer require phpoffice/phpexcel

Mã xuất dữ liệu trong index.php:

public function exportData()
{
    if ($this->request->isPost()) {
        set_time_limit(0);
        $selectedIds = $this->request->post('selectedIds');

        $spreadsheet = new \PHPExcel();
        $spreadsheet->getProperties()->setTitle("Danh sách người dùng");

        // Cấu hình cột tự động điều chỉnh kích thước
        $activeSheet = $spreadsheet->getActiveSheet();
        $activeSheet->getColumnDimension('A')->setAutoSize(true);
        $activeSheet->getColumnDimension('B')->setAutoSize(true);
        $activeSheet->getColumnDimension('C')->setWidth(35);

        // Thêm tiêu đề cột
        $activeSheet->setCellValue('A1', 'ID')
                    ->setCellValue('B1', 'Mã số hợp đồng')
                    ->setCellValue('C1', 'Tên người dùng');

        // Lấy danh sách dữ liệu từ cơ sở dữ liệu
        $dataList = $this->model->select();

        foreach ($dataList as $index => $item) {
            $rowIndex = $index + 2; // Bắt đầu từ dòng thứ hai
            $activeSheet->setCellValue('A' . $rowIndex, $item['id'])
                        ->setCellValue('B' . $rowIndex, $item['contract_number'])
                        ->setCellValue('C' . $rowIndex, $item['full_name']);
        }

        // Tạo tên tệp và gửi xuống trình duyệt
        $fileName = "Danh_sach_nguoi_dung_" . date("YmdHis") . ".xlsx";
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="' . $fileName . '"');
        header('Cache-Control: max-age=0');

        $writer = \PHPExcel_IOFactory::createWriter($spreadsheet, 'Excel2007');
        $writer->save('php://output');
        exit;
    }
}

Thẻ: FastAdmin PHPExcel BootstrapTable

Đăng vào ngày 12 tháng 7 lúc 00:24