phpspreadsheet setCellValue is not writing - php

I am uploading a excel file, reading the contents and writing to a new excel file using phpspreadsheet.
I am trying to create a excel file.
I am writing into cells using the following code
$writesheet->setActiveSheetIndex(0)->setCellValue('A1','myemail#gmail.com');
these lines
echo 'valid';
echo $cell;
echo $toemail;
print all the values correctly.
But this line of code is not working..
Full code:
<?php
include '../includes/common.php';
include "class.emailvalidator.php";
/////////////////////////////////////EXCEL READER ////////////////////////////////
if(!empty($_FILES)){
require 'spreadsheet/vendor/autoload.php';
$file = $_FILES['files']['tmp_name'];
$file_name = $_FILES['files']['name'];
$upload_path = 'files/'.$file_name;
if(move_uploaded_file($file,$upload_path)){
$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($upload_path);
$worksheet = $spreadsheet->getActiveSheet();
$highestRow = $worksheet->getHighestRow();
for ($row = 1; $row <= $highestRow; ++$row) {
$toemail = $worksheet->getCellByColumnAndRow(1, $row)->getValue();
$fromemail = 'admin#myimsuite.com';
$details = verifyEmail($fromemail,$toemail,true);
$writesheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
$cell = 'A'.$row;
if($details[0]== 'valid'){
echo 'valid';
echo $cell;
echo $toemail;
$writesheet->setActiveSheetIndex(0)->setCellValue($cell, $toemail);
}elseif($details[0]== 'invalid'){
}
}
if(file_exists($upload_path)){
unlink($upload_path);
}
$writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($writesheet);
$fxls ='excel-file_1.xlsx';
$writer->save($fxls);
if(file_exists($fxls)){
//force_download($fxls);
}
}
die();
}
function force_download($filename) {
$filedata = #file_get_contents($filename);
// SUCCESS
if ($filedata)
{
// GET A NAME FOR THE FILE
$basename = basename($filename);
// THESE HEADERS ARE USED ON ALL BROWSERS
header("Content-Type: application-x/force-download");
header("Content-Disposition: attachment; filename=$basename");
header("Content-length: " . (string)(strlen($filedata)));
header("Expires: ".gmdate("D, d M Y H:i:s", mktime(date("H")+2, date("i"), date("s"), date("m"), date("d"), date("Y")))." GMT");
header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
// THIS HEADER MUST BE OMITTED FOR IE 6+
if (FALSE === strpos($_SERVER["HTTP_USER_AGENT"], 'MSIE '))
{
header("Cache-Control: no-cache, must-revalidate");
}
// THIS IS THE LAST HEADER
header("Pragma: no-cache");
// FLUSH THE HEADERS TO THE BROWSER
flush();
// CAPTURE THE FILE IN THE OUTPUT BUFFERS - WILL BE FLUSHED AT SCRIPT END
ob_start();
echo $filedata;
}
// FAILURE
else
{
die("ERROR: UNABLE TO OPEN $filename");
}
}
/////////////////////////////////////EXCEL READER ////////////////////////////////
////////////////////////Email Related//////////////////////////////
//var_dump($log);
////////////////////////End Email Related//////////////////////////////
$objSmarty->assign("page",'bannerindex');
$objSmarty->setTemplateDir("../templates");
$objSmarty->display("email_validator.tpl");
?>

Try running $writer->setPreCalculateFormulas(false); - fixed it for me

Related

Getting warning while opening Excel file after writing a table to it using PHP

I have the following code which writes a table to Excel file. Once The file gets downloaded but while opening it, getting warning
The file format and Extension of file.xls do not match. The file could
be corrected or unsafe. Unless you trust its source don't open it.
How to resolve this issue?
header('Content-type: application/vnd.ms-excel');
header("Content-Disposition: attachment; filename=$file_name".date("d_m_Y_H_i_s").".xls");
header("Cache-Control: no-cache, no-store, must-revalidate");
header("Pragma: no-cache");
header("Expires: 0");
ob_clean();
// $res in next line will have a table which I get after processing.
$row = $res->getRowAssoc();
$heading = false;
while ($row != null)
{
if(!$heading) {
for ($ii = 0; $ii < $res->getColumnCount(); $ii++)
{
$field_name = $res->getColumnName($ii);
$field_names[$ii] = $util->get_mls_text($field_name);
}
echo implode("\t", $field_names) . "\r\n";
}
$heading = true;
echo implode("\t", $row) . "\r\n";
$row = $res->getRowAssoc();
}

PHP table to Excel file

I can't figure out how to export a php table to an existing Excel file.
I'm new in php and until now I didn't understand how can I do that.
From my search I saw that it's needed a while and foreach statement.
<?php
$sql_data = date('d.m.Y', strtotime('-1days'));
require(realpath(dirname(__FILE__)."/PHPExcel-1.8/Classes/PHPExcel.php"));
$conn = oci_connect('USER', 'PASS', 'dark:1521/DAR');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
Else {echo 'Connection successfully !';
}
$parametri = oci_parse($conn, "SELECT * FROM TABLE_1 WHERE TO_DATE('${sql_data}','DD.MM.YYYY') BETWEEN T_FROM AND T_TILL");
oci_execute($parametri);
echo "<table border='1'>\n";
while ($row = oci_fetch_array($parametri, OCI_ASSOC+OCI_RETURN_NULLS)) {
echo "<tr>\n";
foreach ($row as $item) {
echo " <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : " ") . "</td>\n";
}
echo "</tr>\n";
}
echo "</table>\n";
$objPHPExcel = new PHPExcel();
$objPHPExcel->setActiveSheetIndex(0);
$objPHPExcel->getActiveSheet()->SetCellValue('A1', 'UD_NAME');
$objPHPExcel->getActiveSheet()->SetCellValue('B1', 'UD_CODE');
$objPHPExcel->getActiveSheet()->SetCellValue('C1', 'TECH_TYPE');
$objPHPExcel->getActiveSheet()->SetCellValue('D1', 'PPE_NAME');
$H_col = $objPHPExcel -> setActiveSheetIndex(0)->getHighestColumn();
$nr_col = PHPExcel_Cell::columnIndexFromString($H_col);
$nr_row = $objPHPExcel -> setActiveSheetIndex(0)->getHighestRow();
$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
$objWriter->save(str_replace('.php', '.xlsx', __FILE__));
?>
function saveExcelFile($objPHPExcel, $file){
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: ' . $file . ';filename="01simple.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;
}
try this instead of
$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
$objWriter->save(str_replace('.php', '.xlsx', __FILE__));
try to run phpexcel, "header was sent error" you can't use "echo" before headers
require(realpath(dirname(__FILE__)."/PHPExcel-1.8/Classes/PHPExcel.php"));
function saveExcelFile($objPHPExcel, $file){
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: ' . $file . ';filename="01simple.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;
}
$objPHPExcel = new PHPExcel();
$objPHPExcel->setActiveSheetIndex(0);
$objWorksheet = $objPHPExcel->getActiveSheet();
$objWorksheet->SetCellValue('A1', 'UD_NAME');
$objWorksheet->SetCellValue('B1', 'UD_CODE');
$objWorksheet->SetCellValue('C1', 'TECH_TYPE');
$objWorksheet->SetCellValue('D1', 'PPE_NAME');
saveExcelFile($objPHPExcel, 'attachment');
i don't know how this code below works, but test it separate
$sql_data = date('d.m.Y', strtotime('-1days'));
$conn = oci_connect('USER', 'PASS', 'dark:1521/DAR');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
Else {echo 'Connection successfully !';
}
$parametri = oci_parse($conn, "SELECT * FROM TABLE_1 WHERE TO_DATE('${sql_data}','DD.MM.YYYY') BETWEEN T_FROM AND T_TILL"
oci_execute($parametri);
echo "<table border='1'>\n";
while ($row = oci_fetch_array($parametri, OCI_ASSOC+OCI_RETURN_NULLS)) {
echo "<tr>\n";
foreach ($row as $item) {
echo " <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : " ") . "</td>\n";
}
echo "</tr>\n";
}
echo "</table>\n";

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 ?

While downloading a zip file from server my PHP website get stucked

I have made a script which zips certain files on server and downloads but issue is while zip is downloading i can't navigate any where on the site. it get stucked until download is not finished or cancelled. i am using below code for making a zip and downloading it
<?php
$files = $_SESSION['cart']['all'];
function createZip($files, $zip_file) {
$zip = new ZipArchive;
if ($zip->open($zip_file, ZipArchive::OVERWRITE) === TRUE) {
foreach ($files as $file) {
if ($file->songType == "1") {
$zip->addFile('assets/songs/' . $file->filePath, $file->filePath);
} else if ($file->songType == "2") {
$zip->addFile('assets/videos/' . $file->filePath, $file->filePath);
}
}
$zip->close();
$_SESSION['cart'] = array();
$_SESSION['cart']['temp'] = array();
$_SESSION['cart']['all'] = array();
return true;
}
else
return false;
}
$temp = 'file.zip';
$pp111 = $temp;
if (createZip($files, $pp111)) {
// header('Content-Type: application/octet-stream');
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"); //Update modified time to current time.
header("Content-Length: " . filesize($pp111)); //file size
header("Content-Disposition: attachment; filename=\"" . stripslashes($pp111) . "\""); //give the file a name.
ob_clean();
flush();
readfile($pp111); // now start reading the file on your server to start downloading to user's desktop */
// unlink($pp111);
ob_end_flush();
ob_end_clean();
exit();
} else {
exit();
}
?>
If you don't close the session, the session file remains locked for all other requests from the same user. If download takes 60 seconds, user has to wait 60 seconds.
You should grab all the data you need on top of the script and then close the session to release the file.

Form downloads same ZIP over and over

Thanks to the users community on this forum, I wrote a very simple web form that allows my user to view text files from within their Internet browser.
I have now two functions whereby the text files returned by the search are compressed into a ZIP. Here's my code
function getFilesFromSite() {
$result = null;
$ZIPresult = null;
if (empty($_POST['DBSite'])) { return null; }
$mydir = MYDIR;
$dir = opendir($mydir);
$DBSite = $_POST['DBSite'];
$getfilename = mysql_query("select filename from search_table where site='" . $DBSite . "'") or die(mysql_error());
while ($row = mysql_fetch_array($getfilename)) {
$filename = $row['filename'];
$result .= '<tr><td>' . $filename . '</td></tr>';
$ZIPresult .= basename($mydir) . '/' . $filename.' ';
}
if ($result) {
$result = "<table><tbody><tr><td>Search Results.</td></tr> $result</table>";
shell_exec("/bin/rm -f SearchResult.zip;/usr/bin/zip -9 SearchResult.zip ". $ZIPresult ." > /dev/null ");
//header for forced download
header("Pragma: public");
header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
$fileName = 'SearchResult.zip';
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Transfer-Encoding: binary");
header('Content-type: application/zip');
header("Content-length: " . filesize($fileName));
header('Content-Disposition: attachment; filename="' . $fileName . '"');
ob_start(); // Starts output buffering.
readfile($fileName); // "Outputs" the file.
$content = ob_get_flush(); // Grabs the output and assigns it to a variable.
print base64_encode($content);
}
function getFilesFromError() {
//Just a copy paste from above with different input parameter...
}
The problem is that the ZIP file with the contents from whatever search was done first gets downloaded over and over again. For instance, the results from getFilesFromSite() will always get downloaded even though I did a search with getFilesFromError() afterwards.
I suspect my headers are incorrectly set but I am not sure where.
PS: The new ZipArchive() library/class is not available on our production environment so I chose to use the Unix utility ZIP instead.
Using Base64 was actually not working for reasons well stated here. Instead, I turned zlib compression off and reverted back to using binary as output format. Finally, I set Content-Type to application/octet-stream in my header. Everything is working fine now ; here's my code:
function getFiles() {
ini_set('zlib.output_compression', 'Off');
$result = null;
$ZIPresult = null;
$cleanup = null;
$output = null;
$fileName = null;
//remove old zip if any
$cleanup = shell_exec("/bin/rm -f SearchResult.zip");
error_log("SHELL OUTPUT=>" . $cleanup, 0);
//test
if (empty($_POST['DBRIDs'])) { return null; }
$mydir = MYDIR; // set from the CONSTANT
$dir = opendir($mydir);
$DBRIDs = $_POST['DBRIDs'];
$getfilename = mysql_query("select /*! SQL_CACHE */ filename from automation where rid in (" . $DBRIDs . ")") or die(mysql_error());
while ($row = mysql_fetch_array($getfilename)) {
$filename = $row['filename'];
$result .= '<tr><td>' . $filename . '</td></tr>';
$ZIPresult .= basename($mydir) . '/' . $filename.' ';
}
if ($result) {
$result = "<table><tbody><tr><td>Search Results.</td></tr> $result</table>";
$output = shell_exec("/usr/bin/zip SearchResult.zip ". $ZIPresult ." ");
error_log("SHELL OUTPUT=>" . $output, 0);
$fileName = 'SearchResult.zip';
error_log("ZIP FILENAME=>" . $fileName, 0);
if (file_exists($fileName)) {
//header for forced download
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($fileName));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($fileName));
ob_clean();
flush();
readfile($fileName);
exit;
}
}
return $result;
}
Thanks to all for taking the time!!

Categories