Export Excel
function export_active_sheet($file_type = '.xlsx')
{
$objPHPExcel = new PHPExcel(); // Create new PHPExcel object
$headings = array(
'Title 1',
'Title 2',
'Title 3'
);
$head_column = 'A';
foreach ($headings as $head_title) {
$objPHPExcel->getActiveSheet() // Sheet object
->setCellValue($head_column . '1', $head_title) // Setting heading value
->getStyle($head_column . '1') // Pointing Column for styling
->getFont() // Getting column's font object of selected column
->setBold(true); // Setting font weight to bold of selected column
$head_column++;
}
$data_list = array(); // Contains list of data that will be inserted into export sheet
if ($data_list) {
$x = 2;
foreach ($data_list as $data) {
$objPHPExcel->getActiveSheet()
->setCellValue('A' . $x, $data['value_1']) // Setting cell value
->getStyle('A' . $x) // Pointing Column for styling
->getAlignment() // Getting column's alignment object of selected column
->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_LEFT); // Setting column's text alignment to left
$objPHPExcel->getActiveSheet()
->setCellValue('B' . $x, $data['value_2'])
->getStyle('B' . $x)
->getAlignment()
->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
$objPHPExcel->getActiveSheet()
->setCellValue('C' . $x, $data['value_3'])
->getStyle('C' . $x)
->getAlignment()
->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
$x++;
}
// Setting cell width according to the internal text width
foreach ($objPHPExcel->getAllSheets() as $sheet) {
// Iterating through all the columns
// The after Z column problem is solved by using numeric columns; thanks to the columnIndexFromString method
for ($col = 0; $col <= PHPExcel_Cell::columnIndexFromString($sheet->getHighestDataColumn()); $col++) {
$sheet->getColumnDimensionByColumn($col)->setAutoSize(true);
}
}
}
$objActSheet = $objPHPExcel->getActiveSheet();
$export_file_name = 'FILE_NAME-' . rand(100000, 999999) . '-[' . date('d-m-y') . ']';
$objActSheet->setTitle('File Title - ' . date('M d, Y'));
// Redirect output to a client’s web browser (Excel5)
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment; filename="' . $export_file_name . '.' . $file_type .'"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
if (ob_get_contents() || ob_get_length()) {
ob_end_clean();
}
// Downloading export file
$objWriter->save('php://output'); exit;
}