I am using PHPExcel to read an excel template, populate the data, and ask the user to download the file.
generate_excel.php
$objPHPExcel = PHPExcel_I
I looked for ways to pass JSON data with ajax to PHP and return an excel file (MySQL and PHPExcel) for the user to save. I looked around and put some pieces together, hope it can help someone:
jQuery:
$("#exportBotton").on("click",function(event) {
event.preventDefault();
// create json object;
str_json = JSON.stringify({"key01":val01, "key02":val02, "key03":val03});
$.ajax({
type: "post",
data: str_json,
url: "../../includes/dbSelect_agentFormExport.php",
dataType: "json",
success: function(output){
// output returned value from PHP t
document.location.href =(output.url);
}
});
});
PHP:
$str_json = file_get_contents('php://input');
$objPHPExcel = new PHPExcel();
// here i populated objPHPExcel with mysql query result.....
function saveExcelToLocalFile($objWriter){
// make sure you have permission to write to directory
$filePath = '../tmp/saved_File.xlsx';
$objWriter->save($filePath);
return $filePath;
}
$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
$response = array(
'success' => true,
'url' => saveExcelToLocalFile($objWriter)
);
echo json_encode($response);
exit();