Đọc dữ liệu MySQL export Excel
Như tiêu đề, chúng ta export dữ liệu từ cơ sở dữ liệu MySQL rồi xuất ra file excel và lưu về máy trạm đang thao tác.
<?php
// Include thư viện PHPExcel_IOFactory vào
include 'Classes/PHPExcel/IOFactory.php';
// Loại file cần ghi là file excel phiên bản 2007 trở đi
$fileType = 'Excel2007';
// Tên file cần ghi
$fileName = 'product_import.xlsx';
// Load file product_import.xlsx lên để tiến hành ghi file
$objPHPExcel = PHPExcel_IOFactory::load("product_import.xlsx");
// Giả sử chúng ta có mảng dữ liệu cần ghi như sau
$array_data = array(
0 => array('name' => 'Hieu', 'email' => ' This email address is being protected from spambots. You need JavaScript enabled to view it. ', 'phone' => '0123456789', 'address' => 'address 1'),
1 => array('name' => 'Nam', 'email' => ' This email address is being protected from spambots. You need JavaScript enabled to view it. ', 'phone' => '0124567892', 'address' => 'address 2'),
2 => array('name' => 'Tuan', 'email' => ' This email address is being protected from spambots. You need JavaScript enabled to view it. ', 'phone' => '09764346789', 'address' => 'address 3'),
3 => array('name' => 'Mai', 'email' => ' This email address is being protected from spambots. You need JavaScript enabled to view it. ', 'phone' => '09876543356', 'address' => 'address 4'),
4 => array('name' => 'Thao', 'email' => ' This email address is being protected from spambots. You need JavaScript enabled to view it. ', 'phone' => '0975458979', 'address' => 'address 5'),
);
// Thiết lập tên các cột dữ liệu
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A1', "STT")
->setCellValue('B1', "Name")
->setCellValue('C1', "Email")
->setCellValue('D1', "Phone")
->setCellValue('E1', "Address");
// Lặp qua các dòng dữ liệu trong mảng $array_data và tiến hành ghi dữ liệu vào file excel
$i = 2;
foreach ($array_data as $value) {
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue("A$i", "$i")
->setCellValue("B$i", $value['name'])
->setCellValue("C$i", $value['email'])
->setCellValue("D$i", $value['phone'])
->setCellValue("E$i", $value['address']);
$i++;
}
//Khởi tạo đối tượng PHPExcel_IOFactory
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, $fileType);
// Tiến hành ghi file
$objWriter->save($fileName);
Sau lệnh trên php sẽ lưu file ở server, hiển nhiên người dùng luôn muốn ghi file tại máy trạm của mình. Ta có thể chỉ định file được tải về ngay khi tạo bằng cách bổ sung một header trước khi save
//header('Content-type: application/vnd.ms-excel');
header(‘Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet’);
header('Content-Disposition: attachment; filename="data.xls"');
header(‘Cache-Control: max-age=0’);
//PHPExcel_IOFactory::createWriter($excel, 'Excel2007')->save('php://output');
$objWriter->save('php://output');
Để tham khảo thêm thông tin bạn truy cập trang web sau: https://phpspreadsheet.readthedocs.io/en/latest/topics/recipes/