<?php
require $_SERVER['DOCUMENT_ROOT'].'/vendor/autoload.php';
// var_dump(str_replace('\"','"',$_POST['excelList']));
$datas = json_decode(str_replace('\"','"',$_POST['excelList']));
$heads = json_decode(str_replace('\"','"',$_POST['excelHead']));
$viewData =[];
foreach ($datas as $DataItem ) {
$data=[];
foreach ($heads as $headsItem ) {
$viewDatakey=$headsItem -> key;
$data[] = $DataItem ->$viewDatakey;
}
$viewData[] =$data;
}
//var_dump($viewData);
$keys = array_keys((array)$datas[0]);
$abc=[];
for( $i=0, $a='A'; $i <count( $keys)+1 ; $i++,$a++ ) {
$abc[$i]=$a;
}
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$h=0;
foreach ($heads as $key ) {
// var_dump($key );
$cellName = $abc[$h].'1';
$width=20;
if(is_numeric($key -> width) ) $width=ceil(($key -> width)/6);
//echo $abc[$h] ;
$sheet->getColumnDimension($abc[$h])->setWidth($width );
$sheet->getRowDimension('1')->setRowHeight(20);
$sheet->setCellValue($cellName, $key->label);
$sheet->getStyle($cellName)->getFont()->setBold(true);
$sheet->getStyle($cellName)->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
$sheet->getStyle($cellName)->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
$sheet->getStyle($cellName)->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('dee2e6');
$sheet->getStyle($cellName)->getBorders()->getAllBorders()->setBorderStyle(\PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN);
$h++;
}
$r=1;
for($i=0;$i<count($viewData);$i++) {
$keys = $viewData[$i];
// var_dump( $keys);
$r=0;
foreach($keys as $key){
$sheet->setCellValue($abc[$r].($i+2),$key );
$sheet->getRowDimension($r)->setRowHeight(20);
$sheet->getStyle($abc[$r].($i+2),$key)->getBorders()->getAllBorders()->setBorderStyle(\PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN);
$r++;
}
// echo "\n";
}
$filename = $_POST["fileName"];
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment; filename="'.$filename.'.xlsx"');
$writer = new Xlsx($spreadsheet);
$writer->save('php://output');