PHPExcel export HTML table to xlsx



PHP Snippet 1:

<?php  
$conn = new mysqli('localhost', 'root', '');  
mysqli_select_db($conn, 'xlsexport');  
$setSql = "SELECT `ur_Id`,`ur_username`,`ur_password` FROM `tbl_user`";  
$setRec = mysqli_query($conn, $setSql);  
$columnHeader = '';  
$columnHeader = "Sr NO" . "\t" . "User Name" . "\t" . "Password" . "\t";  
$setData = '';  
while ($rec = mysqli_fetch_row($setRec)) {  
    $rowData = '';  
    foreach ($rec as $value) {  
        $value = '"' . $value['id'] . '"' . "\t".'"' . $value['ur_username'] . '"'."\t".'"' . $value['ur_password'] . '"';  
        $rowData .= $value;  
    }  
    $setData .= trim($rowData) . "\n";  
}  
header("Content-type: application/octet-stream");  
header("Content-Disposition: attachment; filename = User_Detail_Reoprt.xlsx");  
header("Pragma: no-cache");  
header("Expires: 0");  
echo ucwords($columnHeader) . "\n" . $setData . "\n";  
?>

PHP Snippet 2:

<?php

require_once "../Classes/PHPExcel.php";

$objPHPExcel = new PHPExcel();

header('Content-Type: application/vnd.ms-excel; charset=utf-8');
header('Content-Disposition: attachment;filename="helloworld.xls"');

$objPHPExcel->setActiveSheetIndex(0);
$objPHPExcel->getActiveSheet()->getCell('A20')->setValue("TEST PHPEXCEL");
$objPHPExcel->getActiveSheet()->setTitle('Chesse1');

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
ob_end_clean();
$objWriter->save('php://output');

?>

PHP Snippet 3:

<?php
if (function_exists('mb_internal_encoding')) {
    $oldEncoding=mb_internal_encoding();
    mb_internal_encoding('latin1');
}

require_once 'addons/PHPExcel/PHPExcel/IOFactory.php'; //Update your Path for PHPExcel Class
$objPHPExcel = new PHPExcel();

$sheet = $objPHPExcel->getActiveSheet();
$sheet->setTitle("Template Title");

$sheet->getColumnDimension('A')->setWidth(30);

$sheet->SetCellValue('A1', 'hello world!');

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');

if (function_exists('mb_internal_encoding')){
    mb_internal_encoding($oldEncoding); 
}

header('Content-Type: application/vnd.ms-excel');
header("Content-Disposition: attachment;filename=helloworld.xlsx");
header('Cache-Control: max-age=0');

$objWriter->save('php://output');
?>