AJAX call PHPExcel output file is empty - php

I start with this code:
index.html:
$("button").click(function(){
$.ajax({
type: "POST",
url: "htmltable_to_excel/savexls.php",
cache: false,
data: JSON.stringify({'name': 'test'}),
dataType: 'text',
contentType: 'text/plain',
async: false,
success: function(result)
{
alert(result);
//window.open("htmltable_to_excel/savexls.php",'_blank');
}
});
savexls.php:
$val = file_get_contents('php://input');
$json = json_decode($val, true);
echo $json['name'];
It is return 'test'. AJAX call seems good.
I have code for created xlsx via PHPExcel:
savexls.php:
require_once 'PHPExcel.php';
$val = file_get_contents('php://input');
$json = json_decode($val, true);
$objPHPExcel = new PHPExcel();
$objPHPExcel->setActiveSheetIndex(0);
$objPHPExcel->getActiveSheet()->setCellValue('A1', $json['name']);
// Redirect output to a client’s web browser (Excel2007)
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
ob_clean();
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; charset=utf-8');
header('Content-Disposition: attachment;filename="01simple.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->save('php://output');
But when I open the created xlsx file cell is empty. I forgetting something here? What could be the problem? Does anyone have an idea? Thanks!

Related

PhpSpreadsheet : SUMIF formula is not working

What is the expected behavior?
I tried to add the formula =SUMIF, but this is not working. An error occure and the formula is deleted when I open the excel file
What is the current behavior?
When the code try to calculate the formula, this is bugging
What are the steps to reproduce?
sumif.xlsx : Check this page : https://github.com/PHPOffice/PhpSpreadsheet/issues/892 to download the xlsx
<?php require 'vendor/autoload.php';
set_time_limit(-1);
//error_reporting(0);
$reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader("Xlsx");
$objPHPExcel = $reader->load("sumif.xlsx");
$objPHPExcel->setActiveSheetIndex(1);
for($count = 1 ; $count <= 10; $count++)
{
$objPHPExcel->getActiveSheet()->setCellValue('D'.$count, '=SUMIF(Résumé!D$2:D$22;B'.$count.';Résumé!F$2:F$22)');
}
$objPHPExcel->setActiveSheetIndex(0);
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="paiement_'.date('Y-m-d').'.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 = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($objPHPExcel);
$objWriter->setPreCalculateFormulas(false);
$objWriter->save('php://output');
/**/
?>
Which versions of PhpSpreadsheet and PHP are affected?
PHP 7.0 and PhpSpreadsheet 1.6.0
On the formula string, try using , instead of ; like this:
'=SUMIF(Résumé!D$2:D$22,B'.$count.',Résumé!F$2:F$22)'

PHPExcel writer returns empty file

Im currently writing a data export using PHPExcel and keep getting an empty file.
I've made a test script that should give me an excel file with 3 test cells filled but it also gives me an empty excel file.
When i print_r the $objphpexcel it still shows that the cells are filled.
But when i print_r the writer, it only has the header data available and no cell content..
<?php
include_once 'models/PHPExcel.php';
include_once 'models/PHPExcel/IOFactory.php';
$objPHPExcel = new PHPExcel();
// Set document properties
$objPHPExcel->getProperties()->setCreator('Company')
->setLastModifiedBy('User')
->setTitle('Sample_title');
// Add header (first row) data
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A1', 'EXCEL EXPORT')
->setCellValue('B1', 'TEST')
->setCellValue('C1', 'CEL');
$next_excelrow=2;
//ITERATION TROUGH DATA HERE
// Rename worksheet
$objPHPExcel->getActiveSheet()->setTitle('A');
// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$objPHPExcel->setActiveSheetIndex(0);
//echo'<pre>'.print_r($objPHPExcel,true).'</pre>';exit; <-- this print_r still has the data
// Redirect output to a client’s web browser (Excel5)
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="sample_export.xls"');
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
//header('Content-Type: text/html; charset=UTF-8');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
As you can see I've already narrowed it down to a simple export and still an empty corrupt file is what i get served as a download..
Can anyone help?
Thanks!
try to change $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
to $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="file.xlsx"');
header('Cache-Control: max-age=0');
header('Cache-Control: max-age=1');
header ('Expires: '.gmdate('D, d M Y H:i:s').' GMT');
header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
header ('Cache-Control: cache, must-revalidate');
header ('Pragma: public');
$objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('file.xlsx');
try to save it to file like example, not to php://output. Works for me.
Since PHPExcel is deprecated I'm moving to PHPSpreadsheet

PHPExcel using Ajax to download file on Wordpress

I am making a report on Wordpress where i am using PhpExcel to make an excel file and download it. I am doing this by using Ajax. The problem with this is that when i get the response, the popup window doesn't display and hence can't download the file.
$.ajax({
url: ajaxurl,
dataType: 'json',
data: {poll_id: _id, action: 'admin_poll_by_id'},
method: 'POST',
success: function(rs) {
alert('Report generated');
}
});
I can guarantee that the excel file is being generated because it returns a 200 response, and displays some weird characters on chrome networks response. This is my php code before the exit.
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="' . $fileName . '"');
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('Content-Type: text/html; charset=UTF-8');
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, 'Excel5');
$objWriter->save('php://output');
Any help would be appreciated

$_POST data to phpExcel

I am trying to export data from a html table to an excel file using phpExcel. The issue I am having is that I cannot seem to get the data through to it.
I have the following jquery code which runs on a button press to get the data out of the table and post it to the php code.
export data jquery
function storeTblValues()
{
var tableData = new Array();
$('#LogsTable tr').each(function(row, tr)
{
if(row == 0) //Table Headers
{
tableData[row] =
{
"LogDate" : $(tr).find('th:eq(0)').text(),
"LogType" : $(tr).find('th:eq(1)').text(),
"StartTime" : $(tr).find('th:eq(2)').text(),
"FinishTime" : $(tr).find('th:eq(3)').text(),
"Duration" : $(tr).find('th:eq(4)').text()
}
}
else //Table data
{
tableData[row] =
{
"LogDate" : $(tr).find('td:eq(0)').text(),
"LogType" : $(tr).find('td:eq(1)').text(),
"StartTime" : $(tr).find('td:eq(2)').text(),
"FinishTime" : $(tr).find('td:eq(3)').text(),
"Duration" : $(tr).find('td:eq(4)').text(),
}
}
});
return tableData;
}
function exportToExcel()
{
var tableData;
tableData = $.toJSON(storeTblValues());
var tmp = "pTableData=" + tableData;
$.ajax({
type: 'POST',
url: 'create_export_files.php',
data : tmp,
success : function(data)
{
window.location = 'create_export_files.php';
}
});
}
Top bit of the php file receiving the data
Create_export_files.php
$tableData = "";
if (isset($_POST["pTableData"]))
{
$tableData = $_POST["pTableData"];
$tableData = json_decode($tableData, TRUE);
}
else
{
$tableData = "empty";
}
generateExcel($tableData);
function generateExcel($tableData)
{
/** Include PHPExcel */
require_once dirname(__FILE__) . '/../Classes/PHPExcel.php';
// Create new PHPExcel object
$objPHPExcel = new PHPExcel();
// Add some data
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A1', 'hello')
->setCellValue('B2', 'world!')
->setCellValue('C1', 'Hello')
->setCellValue('D2', 'world!');
// Rename worksheet
$objPHPExcel->getActiveSheet()->setTitle('Simple');
// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$objPHPExcel->setActiveSheetIndex(0);
$filename = 'export '.date('d-m-Y h:i:a').'.xlsx';
// Redirect output to a client’s web browser (Excel2007)
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="'.$filename.'"');
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');
}
I always seem to be going into the else part of the statement. Where am I going wrong?
If I remove the isset bit around the pTableData then the file gets created but is corrupted. Opening it in notepad++ I can see it says pTableData is undefined. Is that because the php file gets run again to make the file download?
try this code:
<?php
$str = "<table>
<tr><td>a</td><td>b</td></tr>
<tr><td>a</td><td>b</td></tr>
<tr><td>a</td><td>b</td></tr>
<tr><td>a</td><td>b</td></tr>
</table>
";
file_put_contents("table.xls",$str);

how to download excel file in internet explorer browser with phpexcel library

i have written code that is working in Mozilla firefox but not working in internet explorer
i cannot solve it. in internet explorer its complete page loding with out popup download .
i need to generete excel file with IE support also.please help me.
here is my code.
$objPHPExcel = new PHPExcel();
$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(18);
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A1', 'Agent Code')
->setCellValue('B1', 'Month');
$i=2;
while($row1=mysql_fetch_array($rs))
{
$month = $row1['smonth']+1;
$month_name = date( 'F', mktime(0, 0, 0, $month) );
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A'.$i, $row1['scode'])
->setCellValue('B'.$i, $month_name)
->setCellValue('C'.$i, $row1['syear']);
$i++;
}
$objPHPExcel->getActiveSheet()->setTitle('Simple');
$objPHPExcel->setActiveSheetIndex(0);
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="01simple.xls"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
exit;
This is complete solution
use
header('Pragma: ');
Your issue is relate with headers were missing.
Try to replace your header code with this following code:
setcookie("fileLoading","true");
// Redirect output to a client’s web browser (Excel2007)
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="'.$viNameFile.'.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');

Categories