$_POST data to phpExcel - php

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);

Related

How to Download Excel file in Angular using File Saver

I had created post form in PHP where on clicking the button it was downloading an excel file and I had some form data also posted to the URL and file used to download successfully with plain HTML and submit form
In PHP this is function triggered when the form is posted to the file
public function downloadExcel($fileName = '', $addTimeStamp = true) {
$fileName = (!$fileName) ? 'excel_download' : preg_replace('/\s+/', '_', $fileName);
if ($addTimeStamp) {
$fileName .= date('_d_m_Y_H_i_s');
}
$fileName .= '.xlsx';
$this->setActiveSheetIndex(0);
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="' . $fileName . '"');
header('Cache-Control: max-age=0');
header('Cache-Control: max-age=1');
header('Expires: Mon, 26 Jul 1997 05:00:00 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($this, 'Excel2007');
$objWriter->save('php://output');
}
When it was working, I have below thing set in the Request Headers
And it was nothing showing in the response
But now we are trying to migrate frontend to the Angular framework from which we are able to download the file, I have tried his way
downloadTheExport() {
this.downloadfile().subscribe((blob: any) => {
const blobdownload = new Blob([blob], { type: "application/vnd.ms-excel;charset=utf-8" });
saveAs(blobdownload, 'testdata.xls');
});
}
downloadfile(){
const formDataForExport: FormData = new FormData();
formDataForExport.append('export', 'ALL');
return this.http.post('http://localhost:8080/service/exportExcel.php', formDataForExport, {
headers: { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9' }
});
}
And When I am trying to download this in Angular I have observed that when the Call is made in Angular it seems Request header for Content-Type is changed to Content-Type: multipart/form-data; boundary angular and also when I see in the response tab it showing some data as below.
Can you please help me how to achieve downloading in Angular in this situation
It is correct for the Content-Type in your Request header since you indeed post a formDataForExport via php backend.
But the way to handle the response seems wrong. I propose a solution below may help:
Assuming if you are referencing this fileSaver:
https://github.com/Hipparch/file-saver-typescript/blob/master/file-saver.ts
Recommend to include above script and use it since to handle different browser behaviour in saving files it is in complexity and not good for re-implement them.
downloadTheExport() {
this.downloadfile().subscribe((resp: any) => {
const fileSaver: any = new FileSaver();
fileSaver.responseData = resp.body;
fileSaver.strFileName = 'testdata.xls';
fileSaver.strMimeType = 'application/vnd.ms-excel;charset=utf-8';
fileSaver.initSaveFile();
});
}
downloadfile() {
const formDataForExport: FormData = new FormData();
formDataForExport.append('export', 'ALL');
return this.http.post('http://localhost:8080/service/exportExcel.php', formDataForExport, {
headers: { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9' },
responseType: 'blob',
observe: 'response'
});
}
If anyone wants only to download a file from assets, they can use this code:
But you need to mention the location in angular.json
"architect": {
"build": {
"options": {
"assets": [
"src/assets/files"
]
}
}
}

AJAX call PHPExcel output file is empty

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!

Set Memory Limit and Time Limit in PHPExcel

I have many arrays and i print it into excel using PHPExcel. Some times it need many column to write. It is over 5000 column.
The problem is sometime even the column is over from 5000 column, it can be print succeesfully but sometime it show as corrupted file.
I have read this : Why PHPExcel does not allow to write more than 5000 rows
But still im confusing.
This is my code :
<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
date_default_timezone_set('Europe/London');
if (PHP_SAPI == 'cli')
die('This example should only be run from a Web Browser');
/** Include PHPExcel */
require_once 'PHPExcel.php';
// Create new PHPExcel object
$objPHPExcel = new PHPExcel();
// Set document properties
$objPHPExcel->getProperties()->setCreator("Valerian Timothy")
->setLastModifiedBy("Valerian Timothy")
->setTitle("Excel Document")
->setSubject("Data Mining")
->setDescription("Count how many words exists.")
->setKeywords("Data Mining")
->setCategory("Data Mining");
// Add some data
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A1', 'Username')
->setCellValue('B1', 'Jumlah')
->setCellValue('C1', 'Hashtag')
->setCellValue('D1', 'Jumlah')
->setCellValue('E1', 'Etc')
->setCellValue('F1', 'Jumlah')
->setCellValue('G1', 'Date')
->setCellValue('H1', 'Jumlah');
// Miscellaneous glyphs, UTF-8
if($_SESSION['username'] != "")
{
$w = 2;
foreach($_SESSION['username'] as $user => $jumlah)
{
$cellUser = 'A' . $w;
$cellJumlah = 'B' . $w;
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue($cellUser, $user)
->setCellValue($cellJumlah, $jumlah);
$w++;
}
}
if($_SESSION['hashtag'] != "")
{
$x = 2;
foreach($_SESSION['hashtag'] as $hashtag => $jumlah)
{
$cellUser = 'C' . $x;
$cellJumlah = 'D' . $x;
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue($cellUser, $hashtag)
->setCellValue($cellJumlah, $jumlah);
$x++;
}
}
if($_SESSION['etc'] != "")
{
$y = 2;
foreach($_SESSION['etc'] as $etc => $jumlah)
{
$cellUser = 'E' . $y;
$cellJumlah = 'F' . $y;
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue($cellUser, $etc)
->setCellValue($cellJumlah, $jumlah);
$y++;
}
}
if(!empty($_SESSION['tanggal']))
{
$z = 2;
foreach($_SESSION['tanggal'] as $date => $jumlah)
{
$cellUser = 'G' . $z;
$cellJumlah = 'H' . $z;
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue($cellUser, $date)
->setCellValue($cellJumlah, $jumlah);
$z++;
}
}
foreach(range('A','H') as $columnID) {
$objPHPExcel->getActiveSheet()->getColumnDimension($columnID)
->setAutoSize(true);
}
// 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);
$today = strtotime(date('Y-m-d H:i:s'));
// Redirect output to a client’s web browser (Excel2007)
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="Data-Mining'.$today.'.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');
exit;
session_destroy();
?>
Could you help me to fix it ?

Retrieve table in database to phpexcel

I am using php excel export the data in database to Excel format.
I can retrieve all the data from database to Excel ady. But if i wanna to retrieve the column name of the table, how i going to do. Anyone can help?
Here's my code:
<?php
header("Content-Type:application/vnd.ms-excel");
header("Content-Disposition:attachment;filename=product.xls");
header("Pragma:no-cache");
header("Expires:0");
header('Content-Type: text/html; charset=UTF-8');
header("Content-type: application/octetstream");
header('Content-Disposition: attachment; filename="export.csv"');
/** Error reporting */
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
date_default_timezone_set('Europe/London');
if (PHP_SAPI == 'cli')
die('This example should only be run from a Web Browser');
/** Include PHPExcel */
require_once '../Classes/PHPExcel.php';
require_once '../Classes/PHPExcel/Writer/Excel2007.php';
require_once '../Classes/PHPExcel/IOFactory.php';
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("litako", $con);
$objPHPExcel = new PHPExcel();
$res= mysql_query("SELECT * FROM vendorlist ");
/** Error reporting */
error_reporting(E_ALL);
date_default_timezone_set('Europe/London');
$objPHPExcel = new PHPExcel();
if(!$res){
die("Error");
}
$col = 0;
$row = 3;
while($mrow = mysql_fetch_assoc($res)) {
$col = 0;
foreach($mrow as $key=>$value) {
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $value);
$col++;
}
$row++;
}
// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$objPHPExcel->setActiveSheetIndex(0);
// Save Excel 2007 file
$objPHPExcel->setActiveSheetIndex(0);
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="report.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
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
exit;
You already have the column name in your while loop where you call mysql_fetch_assoc. The $key value is the column name. So here is an updated portion of your code:
while($mrow = mysql_fetch_assoc($res)) {
$col = 0;
foreach($mrow as $key=>$value) {
// TODO: Do Something With the Column Name like set the row header. Note this crude code sets it every time. You really just want to do it the first time only.
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, 0, $key);
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row + 1, $value);
$col++;
}
$row++;
}

Opening excel document created by php

I have managed to create an excel document using php however I am getting an error everytime I open the document, even though everything else is fine. the error is the file you are trying to open is in different format than specified by the file extension ...
My code to export to excel:
public function actionExportToExcel() {
//header('Content-type: text/csv');
header('Content-Disposition: attachment; filename="project-report-' . date('YmdHi') .'.xls"');
header("Content-Type: application/ms-excel");
$model=new ViewWebprojectreport('search');
$model->unsetAttributes(); // clear any default values
if(Yii::app()->user->getState('exportModel'))
$model=Yii::app()->user->getState('exportModel');
$dataProvider = $model->search(false);
$dataProvider->pagination->pageSize = $model->count();
// csv header
echo ViewWebprojectreport::model()->getAttributeLabel("StartDATE")."\t".
ViewWebprojectreport::model()->getAttributeLabel("PROJECT")."\t".
"Survey Number\t".
ViewWebprojectreport::model()->getAttributeLabel("ActualEndDate")."\t".
ViewWebprojectreport::model()->getAttributeLabel("OFFICE")."\t".
ViewWebprojectreport::model()->getAttributeLabel("PERCENT")."\t".
ViewWebprojectreport::model()->getAttributeLabel("PERCENTPlanned")."\t".
ViewWebprojectreport::model()->getAttributeLabel("KM")."\t".
ViewWebprojectreport::model()->getAttributeLabel("KMPlanned")."\t".
ViewWebprojectreport::model()->getAttributeLabel("COUNTRY")."\t".
ViewWebprojectreport::model()->getAttributeLabel("AREA")."\t".
ViewWebprojectreport::model()->getAttributeLabel("ASAAREA").
" \r\n";
// csv data
foreach ($dataProvider->getData() as $data) {
//if you want all data use this looop
/*foreach ($data as $key => $value) {
echo $value.",";
}
echo "\r\n";*/
echo "$data->StartDATE\t$data->PROJECT\t".$data->PROJCODE . $data->PROJID ."\t$data->ActualEndDate\t$data->OFFICE\t$data->PERCENT\t$data->PERCENTPlanned\t$data->KM\t$data->KMPlanned\t$data->COUNTRY\t$data->AREA\t$data->ASAAREA\t\r\n";
}
}
I do not want to export as csv but straight into excel format file. What am I missing?
This is because the file is actually basically just a CSV file with an XLS extension to make it open in Excel. See this Microsoft doc for more information: http://support.microsoft.com/kb/948615 - it happens in new versions of Excel. Older ones will happily export them.
The reason for doing it this way was because it is so much simpler to export a CSV file than an Excel one. I'd like to write a proper Excel exporter sometime, but that will take time to read and understand the Excel file format, and I've not had a chance to do that yet.
One option is simply to rename the file name to .csv, and keep the user interface as saying that it is an Excel file (Excel is quite happy to read csv files). Given that Windows tends to hide the file extension, this seems like a fairly attractive option.
It would be helpful solution for solving varied kinds of excel problems - link
let me know if i can help you more.
I used PHPExcel
$objPHPExcel = new PHPExcel();
spl_autoload_register(array('YiiBase', 'autoload'));
$objPHPExcel->getProperties()->setCreator(Yii::app()->user->__userInfo['name'])
->setLastModifiedBy(Yii::app()->user->__userInfo['name'])
->setTitle("Weekly Status")
->setSubject("Weekly Status");
$sheet = $objPHPExcel->setActiveSheetIndex(0);
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();
$model=new ViewWebprojectreport('search');
$model->unsetAttributes(); // clear any default values
if(Yii::app()->user->getState('exportModel'))
$model=Yii::app()->user->getState('exportModel');
$dataProvider = $model->weeklystatus(array(),true,false);
$dataProvider->pagination->pageSize = $model->count();
//data
foreach ($dataProvider->getData() as $data) {
//if you want all data use this looop
$highestColumn = "A";
foreach ($data as $key => $value) {
if(! in_array($key,array("id","PROCESSOR","DEPTCODE","PERCENTPlanned","MCSALE"))){
if($key == "name")
$key = "Client";
else
$key = ViewWebprojectreport::model()->getAttributeLabel("$key");
if($highestRow == 1){
$sheet->setCellValue($highestColumn.$highestRow,$key);
//Yii::log($key,"ERROR");
}
//echo $value.",";
if($highestRow == 1){
$highestRow++;
$sheet->setCellValue($highestColumn.$highestRow,$value);
$highestRow--;
}else
$sheet->setCellValue($highestColumn.$highestRow,$value);
$highestColumn++;
}
}
//Yii::log($highestRow,"ERROR");
if($highestRow == 1)
$highestRow++;
$highestRow++;
//echo "\r\n";*/
//echo "$data->StartDATE\t$data->ProjectEndDate\t$data->PROJECT\t".$data->PROJCODE . $data->PROJID ."\t$data->ActualEndDate\t$data->PROCESSOR\t$data->OFFICE\t$data->DEPTCODE\t$data->PERCENT\t$data->PERCENTPlanned\t$data->KM\t$data->KMPlanned\t$data->MC\t$data->MCSALE\t$data->CATEGORY\t$data->COUNTRY\t$data->AREA\t$data->PROJINFO\t$data->REGION\t$data->ASAAREA\t\r\n";
}
$filename = $_GET['type'].'statusreport_'.date('Y-m-d_H-i-s_T').'.xls';
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 ('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(Yii::app()->params['exportToDir'].$filename);
$objWriter->save('php://output');
Yii::app()->end();

Categories