Hướng dẫn sử dụng lib PHPExcel để xuất file excel trong php
Lượt xem: 4687
Trước tiên các bạn cần require thư viện PHPExcel vào trong project của chúng ta
require_once dirname(__FILE__) ."/libs/PHPExcel/PHPExcel.php";
Bổ sung thêm form chứa button ExportExcel
<div class="card-body">
<form class="needs-validation" novalidate enctype="application/x-www-form-urlencoded" >
<input type="hidden" name="excel" value="1" / >
<button class="btn btn-info" >ExportExcel</button >
</form >
<div >
Bổ sung code PHP để check biến excel và thêm dữ liệu và download file
if(isset($_GET['excel'])) {
$result = mysqli_query($conn,"SELECT * FROM Customers". $where);
// Create new PHPExcel object
$objPHPExcel = new PHPExcel();
// Add some data
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A1', 'Tên khách hàng')
->setCellValue('B1','Điện thoại')
->setCellValue('C1', 'Địa chỉ')
->setCellValue('D1', 'Email');
$key = 0;
while($customer = mysqli_fetch_assoc($result)) {
// Add some data
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A'.($key+2), $customer['CustomerName'])
->setCellValue('B'.($key+2), $customer['Phone'])
->setCellValue('C'.($key+2), $customer['Address'])
->setCellValue('D'.($key+2), $customer['email']);
$key ++;
}
// Rename worksheet
$objPHPExcel->getActiveSheet()->setTitle('Customer');
// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$objPHPExcel->setActiveSheetIndex(0);
// Redirect output to a client’s web browser (Excel2007)
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="customer.xlsx"');
header('Cache-Control: max-age=0');
// If you're serving to IE 9, then the following may be needed
header('Cache-Control: max-age=1');
// If you're serving to IE over SSL, then the following may be needed
header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
header ('Pragma: public'); // HTTP/1.0
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');
exit;
}
Video