PhpExcel Load a dynamic template - php

I am trying to load an excel xlsx file template which is dynamic, I tried with the following method :
$approve_employee_id = $this->input->post('approve_employee_id');
$query = "SELECT * from employee where employee.employee_id='$approve_employee_id'";
$query = $this->db->query($query);
foreach ($query->result() as $value) {
$f_name = $value->f_name;
$s_name = $value->s_name;
$user_name = $value->user_name;
$under_score = "_";
$file_name = $user_name . $under_score . $approve_month_id . $under_score . $approve_year_name;
$folder_name = $approve_month_id . $approve_year_name;
$basedir = $_SERVER['DOCUMENT_ROOT'] . "/timesheet/files";
$this->load->library('excel');
$objPHPexcel = PHPExcel_IOFactory::load("/Applications/MAMP/htdocs/timesheet/files/un_approved/'$file_name'.xlsx");
echo 'Loading template successfull...';
$objWorksheet = $objPHPexcel->getActiveSheet();
}
How can I load the file name in a dynamic way?
The following is one of the file's name : HS103_January_2014

Look at the filename you're trying to load:
"/Applications/MAMP/htdocs/timesheet/files/un_approved/'$file_name'.xlsx"
If the value of $file_name is HS103_January_2014, then this will try to load
/Applications/MAMP/htdocs/timesheet/files/un_approved/'HS103_January_2014'.xlsx
Does it really have single quotes in the actual filename?
Use
$objPHPexcel = PHPExcel_IOFactory::load(
"/Applications/MAMP/htdocs/timesheet/files/un_approved/{$file_name}.xlsx"
);

Related

upload videos file with jwplatform [PHP]

so here is my problem:
I want to use jwplatform-php to upload my video files.
here is my php script: (this is more or less the sample script provided)
<?php
use Jwplayer\JwplatformClient;
header_remove( 'X-Powered-By' );
chdir(dirname(__DIR__));
require 'vendor' . DIRECTORY_SEPARATOR . 'autoload.php';
$secret = "XXXXXXXXXXXXXXXXXXX";
$site_id = "XXXXX";
$jwplatform_api = new JwplatformClient($secret);
$target_file = "test.mp4";
$params = [];
$params['metadata'] = [];
$params['metadata']['title'] = 'PHP API Test Upload';
$params['metadata']['description'] = 'Video description here';
$params['upload'] = [];
$params['upload']['method'] = 'direct';
// Create the example media
$create_response = json_encode($jwplatform_api->Media->create($site_id, $params));
print_r($create_response);
print("\n");
$decoded = json_decode(json_decode(trim($create_response), true), true);
$upload_link = $decoded['upload_link'];
// Upload the media file
$upload_response = $jwplatform_api->Media->upload($target_file, $upload_link);
print_r($upload_response);
print("\n");
And so the error occurs at $create_response he return false.
I think the problem is $target_file = "test.mp4"; that he can't solve even by putting the relative path $target_file = dirname(__FILE__) . DIRECTORY_SEPARATOR ."test.mp4"; he returns to me false.
I don't know what to do and in addition the doc jwplatform-php is almost non-existent
I thank you already for all the help provided and sorry for my approximate English...

How to give path to the file?

Hi I want to save the file in excel format in my local folder. For this I am creating an api which will be scheduled to call at every night and save the data in file every night.
My attempt is :
class SaveExcel
{
function SaveExcel()
{
}
function saveData()
{
$file_result = "";
$database = new Database(Constants::DBHOST, Constants::DBUSER, Constants::DBPASS, Constants::DBNAME);
$dbConnection = $database->getDB();
date_default_timezone_set('Asia/Kolkata');
$date = date('m/d/Y h:i:s a', time());
$DB_TBLName = "location"; //MySQL Table Name
$filename = "LocationHistory(" . $date . ")"; //File Name
//create MySQL connection
$stmt = $dbConnection->prepare("Select * from $DB_TBLName");
$stmt->execute();
$columnHeader = '';
$columnHeader = "loc_id" . "\t" . "user_id" . "\t" . "address" . "\t" . "date_time" . "\t";
$setData = '';
while ($rec = $stmt->FETCH(PDO::FETCH_ASSOC)) {
$rowData = '';
foreach ($rec as $value) {
$value = '"' . $value . '"' . "\t";
$rowData .= $value;
}
$setData .= trim($rowData) . "\n";
}
// file_put_contents('history/' . $filename, $setData);
return ucwords($columnHeader)."\n".$setData."\n";
}
}
?>
By this I am getting the output as :
"Loc_id\tUser_id\tAddress\tDate_time\t\n\"118\"\t\"1\"\t\"19.166488899999997\"\t\"72.8510805\"\t\"16, Aarey Rd, Jay Prakash Nagar, Goregaon East, Mumbai, Maharashtra 400063, India\"\t\"2018-03-03 18:05:45\"\n\"119\"\t\"1\"\t\"19.165215999999997\"\t\"72.8509167\"\t\"MU Chambers, Jay Prakash Nagar, Goregaon West, Mumbai, Maharashtra 400063, India\"\t\"2018-03-03 18:22:14\"\n\"120\"\t\"1\"\t\"19.1651942\"\t\"72.85087469999999\"
now I want to save this data in excel format in local folder.
How can I do this?
Please help.. Thank you.
EDIT :
This code is working well.. Now I just want to give the path to the file. Now its getting saved under the project directory I want to get it saved in another directory. How Can I?
$objPHPExcel = new PHPExcel();
$objPHPExcel->setActiveSheetIndex(0);
$rowCount = 1;
$objPHPExcel->getActiveSheet()->SetCellValue('A'.$rowCount, 'Employee');
$objPHPExcel->getActiveSheet()->SetCellValue('B'.$rowCount, 'Address');
$objPHPExcel->getActiveSheet()->SetCellValue('C'.$rowCount, 'Date Time');
$rowCount++;
while($row = $stmt->FETCH(PDO::FETCH_ASSOC)){
$objPHPExcel->getActiveSheet()->SetCellValue('A'.$rowCount, $user_name);
$objPHPExcel->getActiveSheet()->SetCellValue('B'.$rowCount, $row['address']);
$objPHPExcel->getActiveSheet()->SetCellValue('C'.$rowCount, $row['date_time']);
$rowCount++;
}
$current_date = preg_replace('/\s+/', '', $date);
$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
$name = '/path/to/folder/xyz.xlsx';
$objWriter->save($user_name.$current_date.'.xlsx');
return 'File Saved';
What you are showing here is a TSV (tab-separated values) string, which is readable by Excel, but it's not a full Excel spreadsheet (e.g. you can't have colors etc.). This is good enough for many applications, and it can also be read by any app that reads TSVs (from Notepad++ to LibreOffice), which is an advantage.
However, if you want to create actual Excel files, it's much more difficult. There are libraries out there that do it, like this open-source one: https://github.com/PHPOffice/PhpSpreadsheet
you need to add header of type excel on your code.
$filename = date('m/d/Y h:i:s a', time());
header("Content-Type: application/xls");
header("Content-Disposition: attachment; filename=$filename.xls");
application/xls work on < excel 2007. so if get error on excel, you can change that to application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
in other way, PHPExcel is a good plugin to customize your output excel
hope this help you.

PHPExcel - Call to a member function getCacheData() on null

I am getting an error something like below when writing a file
Error: Call to a member function getCacheData() on null
File E:\websites\d3a-qa\vendor\PHPExcel\PHPExcel\Worksheet.php
Line: 2554
Line 2554:
public function garbageCollect() {
// Flush cache
$this->_cellCollection->getCacheData('A1');
I know this error is coming because $this->_cellCollection is null but I dont know why is it null. I am calling $writer->save($saving_name); where it gives this issue.
I tried doing all sort of things. From backtracing to commenting the disconnectWorksheet code. resetting the variables for PHPExcel object but nothing works.
The funny part is sometimes it works and sometimes it doesn't. There's not much documentation or answers to queries aboout PHPExcel on internet. Therefore at last I have come here so that I could get any answer or at least a hint of what needs to be done.
Thanks in Advance.
EDIT
Here's my code where I am using PHPExcel. It appears that the error is coming at $writer->save($saving_name);.
$parts is an array having several number of XLS that needs to be merged into one XLS sheet.
PS: The error comes only when heavy processing is done (or nearly 45 sheets). For smaller xls counts its working fine.
if(!empty($insertSummary)) {
$PHPExcel = new \PHPExcel();
$PHPExcel = $PHPExcel->createSheet();
$PHPExcel->setTitle(_EXPORT_DES_SUMMARY);
}
foreach ($parts as $part) {
$bigExcel = '';
if(!empty($insertSummary))
$bigExcel = $this->addSummarySheet($insertSummary, $part, $PHPExcel);
$bigExcel = $this->processPartFiles($part, $bigExcel);
$writer = \PHPExcel_IOFactory::createWriter($bigExcel, 'Excel5');
$returnFilename = $dbName . '_' . 'DES' . '_' . date('Y-m-d-h-i-s') . '_' . 'Part_' . ++$count . '.xls';
// name of file, which needs to be attached during email sending
$saving_name = _DES_PATH_WEBROOT . DS . $returnFilename;
$zipFiles[] = $saving_name;
$writer->save($saving_name);
//Log::write('debug', 'Line(' . __LINE__ .') memory_get_peak_usage - ' . memory_get_peak_usage(true));
//Log::write('debug', 'Line(' . __LINE__ .') memory_get_usage - ' . memory_get_usage());
}
EDIT-2
$this->addSummarySheet()
public function addSummarySheet($insertSummary, $part, $PHPExcel) {
$keys = array_keys($part);
$bigExcel = $this->CommonInterface->readXlsOrCsv($insertSummary, false);
//Copy & paste values of range of cells
$cellValuesTitle = $bigExcel->getActiveSheet()->rangeToArray('A1:C1');
$cellValues = $bigExcel->getActiveSheet()->rangeToArray('A' . ($keys[0] + 1) .':C' . ($keys[count($keys) - 1] + 1));
$bigExcel->removeSheetByIndex(0);
$bigExcel->addSheet($PHPExcel);
$bigExcel->getActiveSheet()->fromArray($cellValuesTitle, null, 'A1');
$bigExcel->getActiveSheet()->fromArray($cellValues, null, 'A2');
foreach($keys as $rowCount => $sheet) {
$cellCordinateRow = $rowCount + 2;
$bigExcel->getActiveSheet()->getCell('A' . $cellCordinateRow)->getHyperlink()->setUrl("sheet://'Data $sheet'!A{$cellCordinateRow}");
}
return $bigExcel;
}
$this->CommonInterface->readXlsOrCsv()
public function readXlsOrCsv($filename = null, $unlinkFile = true, $sheetnames = null) {
require_once(ROOT . DS . 'vendor' . DS . 'PHPExcel' . DS . 'PHPExcel' . DS . 'IOFactory.php');
/** Identify the type of $inputFileName **/
$inputFileType = \PHPExcel_IOFactory::identify($filename);
$objReader = \PHPExcel_IOFactory::createReader($inputFileType);
if(!empty($sheetnames)) {
//$objReader->setReadDataOnly(true);
$objReader->setLoadSheetsOnly($sheetnames);
}
$objPHPExcel = $objReader->load($filename);
//$objPHPExcel = \PHPExcel_IOFactory::load($filename);
if ($unlinkFile == true)
$this->unlinkFiles($filename); // Delete The uploaded file
return $objPHPExcel;
}
I've solved the issue I was facing with PHPExcel.
I have changed removed $bigExcel = $this->CommonInterface->readXlsOrCsv($insertSummary, false); from $this->addSummarySheet() and placed it under if(!empty($insertSummary)) { as stated in EDIT 2.
Also, I have added below line of code in $this->addSummarySheet()
$PHPExcelSheet = new \PHPExcel();
$PHPExcelSheet->removeSheetByIndex(0);
$PHPExcel = new \PHPExcel();
$PHPExcel = $PHPExcel->createSheet();
$PHPExcel->setTitle(_EXPORT_DES_SUMMARY);
SO My final code in $this->addSummarySheet() becomes
public function addSummarySheet($insertSummary, $part, $PHPExcel, $summaryExcel) {
$keys = array_keys($part);
//$summaryExcel= $this->CommonInterface->readXlsOrCsv($insertSummary, false);
//Copy & paste values of range of cells
$cellValuesTitle = $summaryExcel->getActiveSheet()->rangeToArray('A1:C1');
$cellValues = $summaryExcel->getActiveSheet()->rangeToArray('A' . ($keys[0] + 1) .':C' . ($keys[count($keys) - 1] + 1));
$PHPExcelSheet = new \PHPExcel();
$PHPExcelSheet->removeSheetByIndex(0);
$PHPExcel = new \PHPExcel();
$PHPExcel = $PHPExcel->createSheet();
$PHPExcel->setTitle(_EXPORT_DES_SUMMARY);
$PHPExcelSheet->addSheet($PHPExcel);
$PHPExcelSheet->getActiveSheet()->fromArray($cellValuesTitle, null, 'A1');
$PHPExcelSheet->getActiveSheet()->fromArray($cellValues, null, 'A2');
foreach($keys as $rowCount => $sheet) {
$cellCordinateRow = $rowCount + 2;
$PHPExcelSheet->getActiveSheet()->getCell('A' . $cellCordinateRow)->getHyperlink()->setUrl("sheet://'Data $sheet'!A{$cellCordinateRow}");
}
return $PHPExcelSheet;
}
Thanks Mark for providing the $this->addSummarySheet() hint. It truly helped.

Laravel 5.1 file upload, File's same name for folder and database

My controller code where i store the file name into a database table and also moving the file to a folder.
The issue is that i am storing the original name of a file in database table, in contrast i am moving files with uniqueid() and time() . It will arise issues in future. because in database table file name and moved file are with different names.
if(Input::hasFile('profile_pic')){
$pic = Input::file('profile_pic');
$mobile->photo1 = $pic[0]->getClientOriginalName();
$mobile->photo2 = $pic[1]->getClientOriginalName();
$mobile->photo3 = $pic[2]->getClientOriginalName();
$mobile->photo4 = $pic[3]->getClientOriginalName();
$mobile->photo5 = $pic[4]->getClientOriginalName();
foreach ($pic as $k=>$file){
if(!empty($file)){
$file->move(public_path() . '/uploads/', time() . uniqid() . '-' . $k . '-laptop');
}
}
}
You can try to use something like that:
if(Input::hasFile('profile_pic')){
$pic = Input::file('profile_pic');
foreach ($pic as $k=>$file){
if(!empty($file)){
$temp = $k+1;
$mobile->photo.$temp = time() . uniqid() . '-' . $k . '-laptop';
$file->move(public_path() . '/uploads/', $mobile->photo.$temp);
}
}
}
You can store both names in your database. Store one as original_name and one as generated_name for example.
And you can serve the file with the original name by retrieving it from the database if you want to let your users download it. It should look like this:
$photo = Photo::find(1);
return response()->download($photo->generated_filename, $photo->filename);

Laravel 5.1 file upload unique name

My controller code where i store the file name into a database table and also moving the file to a folder.
The issue is that i am storing the original name of a file in database table, in contrast i am moving files with uniqueid() and time() . It will arise issues in future. because in database table file name and moved file are with different names.
What i want is to store the file name into database table and move the file to folder with with uniqueid() and time().
Code :
if(Input::hasFile('profile_pic')){
$pic = Input::file('profile_pic');
$mobile->photo1 = $pic[0]->getClientOriginalName();
$mobile->photo2 = $pic[1]->getClientOriginalName();
$mobile->photo3 = $pic[2]->getClientOriginalName();
$mobile->photo4 = $pic[3]->getClientOriginalName();
$mobile->photo5 = $pic[4]->getClientOriginalName();
foreach ($pic as $k=>$file){
if(!empty($file)){
$file->move(public_path() . '/uploads/', time() . uniqid() . '-' . $k . '-laptop');
}
}
}
You will need to store the destination path into a variable and then reuse it to move the file and to store its value in the database
if(Input::hasFile('profile_pic')){
$pic = Input::file('profile_pic');
$mobile->photo1 = $pic[0]->getClientOriginalName();
$mobile->photo2 = $pic[1]->getClientOriginalName();
$mobile->photo3 = $pic[2]->getClientOriginalName();
$mobile->photo4 = $pic[3]->getClientOriginalName();
$mobile->photo5 = $pic[4]->getClientOriginalName();
foreach ($pic as $k=>$file){
if(!empty($file)){
$destinationPath = public_path() . '/uploads/', time() . uniqid() . '-' . $k . '-laptop';
$file->move($destinationPath);
// and you may store the path here to the database
// like yourObject->filePath = $destinationPath;
// yourObject->save();
}
}
}

Categories