Im trying include PHPExcel lib to Yii, put PHPExcel.php in root of extensions, near PHPExcel folder and added that code into config/main.php
// application components
'components'=>array(
'excel'=>array(
'class'=>'application.extensions.PHPExcel',
),
modify /protected/extensions/PHPExcel/Autoloader.php
public static function Register() {
$functions = spl_autoload_functions();
foreach($functions as $function)
spl_autoload_unregister($function);
$functions=array_merge(array(array('PHPExcel_Autoloader', 'Load')), $functions);
foreach($functions as $function)
$x = spl_autoload_register($function);
return $x;
}// function Register()
Then, trying create PHPExcel object $objPHPExcel = new PHPExcel();
but have an error: include(PHPExcel.php) [<a href='function.include'>function.include</a>]: failed to open stream: No such file or directory in Z:\home\yii.local\www\framework\YiiBase.php(418)
try these, it work for me.
Copy files. Copy all files of PHPExcel in ROOT\protected\vendors\PHPExcel. This folder PHPExcel is the folder Classes renamed. Like these:
ROOT\protected\vendors\PHPExcel\
PHPExcel.php
PHPExcel\...
all files php
Load the clases PHPExcel. Modify the file ROOT\index.php. You will change how run the yii app.
$app = Yii::createWebApplication($config);
// adding PHPExcel autoloader
Yii::import('application.vendors.*');
require_once "PHPExcel/PHPExcel.php";
require_once "PHPExcel/PHPExcel/Autoloader.php";
Yii::registerAutoloader(array('PHPExcel_Autoloader','Load'), true);
$app->run();
Test your PHPExcel. Create a action in any controller
public function actionExcel(){
$objPHPExcel = new PHPExcel();
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A1', 'Hello')
->setCellValue('B2', 'world!')
->setCellValue('C1', 'Hello')
->setCellValue('D2', 'world!');
$objPHPExcel->getActiveSheet()->setTitle('Simple');
$objPHPExcel->setActiveSheetIndex(0);
ob_end_clean();
ob_start();
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="test.xls"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
}
Seeing your other question, I guess you have found the answer. Alas ... you have to use the import in the config, not components. Something like this:
// autoloading model and component classes
'import'=>array(
'application.models.*',
'application.components.*',
'application.vendors.phpexcel.classes.*',
),
You should also put phpexcel in a folder called vendors, not extensions. It is third party software and does not extend Yii.
There is also a guide here that works with disabling Yii autoload, instead of disabling PHPExcel autoload.
http://www.yiiframework.com/wiki/101/how-to-use-phpexcel-external-library-with-yii/
Try this:
spl_autoload_unregister(array('YiiBase','autoload'));
Yii::import('ext.phpexcel.Classes.PHPExcel', true);
$objPHPExcel = new PHPExcel();
$activeSheet = $objPHPExcel->getActiveSheet();
spl_autoload_register(array('YiiBase','autoload'));
Related
I need to edit a excel file in php. I've got a simple PHP Spreadsheet.
I use fat-free and the problem is
public function MakeExcel()
{
require 'vendor/autoload.php';
use \vendor\phpoffice\phpspreadsheet\src\PhpSpreadsheet\Spreadsheet ;
use \vendor\phpoffice\phpspreadsheet\src\PhpSpreadsheet\Writer\Xlsx ;
$Spreadsheet = new Spreadsheet();
$sheet = $Spreadsheet->getActiveSheet();
$sheet->setCellValue('A3', 'toto');
$writer = new Xlsx($Spreadsheet);
$writer->save("test.xlsx");
$f3->set('CONTENT','views/dashboard/dashboard_liste.html');
$f3->set('CONTENTJS','views/dashboard/dashboard_liste.js');
echo \Template::instance()->render('views/accueil/accueil.html','text/html');
$this->db = null;
}
use doesn't seem to exist in fat-free so i tried:
$f3->use(\vendor\phpoffice\phpspreadsheet\src\PhpSpreadsheet\Spreadsheet);
Or
$f3->use("\vendor\phpoffice\phpspreadsheet\src\PhpSpreadsheet\Spreadsheet");
and many other it return me the error :
ERROR 500 Call to a member function use() on null
Problem Solved thanks everyone :
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
class MakeExcel extends Controller {
public function MakeExcel(){
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1', 'Hello World !');
$writer = new Xlsx($spreadsheet);
$writer->save('hello world.xlsx');
}
}
First of all seems you use Fat Free wrong. Because $f3 is null.
Second. Probably you are importing classes with wrong namespaces. You can read documentation of PhpSpreadsheet.
Right way:
require 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
You can phisically find this classes and look on the namespace.
Put your import of composer autoload and use block outside of this function.
Make sure you ran composet install
Make your function work without PhpSpreadsheet. And after that try to add other functionality
You need to declare those files in php top area
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
Then in method create object for spreadsheet
$spreadsheet = new Spreadsheet();
Then you can define the border and alignment for xls file like that
$cell_st =[
'font' =>['bold' => true],
'alignment' =>['horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER],
'borders'=>['bottom' =>['style'=> \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN],'top' =>['style'=> \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN]]
];
To Define the Header you can use below code
$spreadsheet->setActiveSheetIndex(0)->mergeCells('A2:D2');
$spreadsheet->setActiveSheetIndex(0)->setCellValue('A2', "<YOUR HEADER>");
$spreadsheet->getActiveSheet()->getStyle('A2:D2')->applyFromArray($cell_st);
And Then define the column names
$spreadsheet->setActiveSheetIndex(0)
->setCellValue('A3', 'ID')
->setCellValue('B3', 'NAME')
->setCellValue('C3', 'CITY')
->setCellValue('D3', 'SALARY');
After all above code now you can start your content in loop like that
$rowcount = 4;
foreach($data_array as $key=>$value){
$spreadsheet->setActiveSheetIndex(0)
->setCellValue('A'.$rowcount, $value['id'])
->setCellValue('B'.$rowcount, $value['name'])
->setCellValue('C'.$rowcount, $value['city'])
->setCellValue('D'.$rowcount, $value['salary']);
$rowcount++;
}
and in last now make object of the Xlsx class to save the excel file
$writer = new Xlsx($spreadsheet);
$file_name = "report.xls';
$file_root_path = "assets/reports/xls/".$file_name;
$file_site_path = "localhost/xls_generate/assets/reports/xls/".$file_name;
$writer->save($file_root_path);
// final xls file path is here
echo $file_site_path;
That's all, Hope this work for you..
I have used https://github.com/PHPOffice/phpspreadsheet this package to download
csv files in codeigniter
When I try to download it shows blank in browser tab and not showing download option
there are no errors
Tried with below code
<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');
require 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
class Reports extends Admin_Controller
{
public function download()
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1', 'Hello World !');
$writer = new Xlsx($spreadsheet);
$writer->save('hello world.xlsx');
}
}
Can any anyone help on that please??.Thanks
Hope this will help you :
require 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
class Reports extends Admin_Controller
{
public function index()
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1', 'Hello World !');
$spreadsheet->setActiveSheetIndex(0);
$filename = 'hello world';
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="'.$filename.'.xlsx"');
header('Cache-Control: max-age=0');
$writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save('php://output');
}
}
for csv just change the extesion .xlsx to .csv (case-sensitive)
The download() function you have there is only for writing a new file. Not anything to do with downloading a file. However I managed to output a file using this code here. I outputted a csv file so I could check it more easily on my server but the premise is still the same with xlsx files.
public function writeFile() {
$this->load->library('Spreadsheet');
$output_file = getcwd() . "/test/hello_world.csv";
$spreadsheet = new Spreadsheet();
$spreadsheet->setActiveSheetIndex(0);
$spreadsheet->getActiveSheet()->setCellValueByColumnAndRow("1", "1", "Hello World!");
$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Csv');
$writer->save($output_file);
}
I think part of your problem was not loading the library correctly using the CodeIgniter nomenclature. If you are trying to upload files I would reccomend using the upload library which comes with CodeIgniter. The documentation can be found here: https://www.codeigniter.com/userguide3/libraries/file_uploading.html
I would then use phpspreadsheet to edit it to your hearts content once it has been uploaded. Hope this helps.
I have followed this tutorial here
https://arjunphp.com/how-to-use-phpexcel-with-codeigniter/
and here
http://www.ahowto.net/php/easily-integrateload-phpexcel-into-codeigniter-framework/
However, I still get the PHPExcel_IOFactory not found error. I haven't found much help in this area. Is there an alternative excel plugin or is there a way to solve this?
This is my controllers construct
public function __construct() {
parent::__construct();
$this->load->library('Excel');
}
This is my controllers upload function
$objReader= PHPExcel_IOFactory::createReader('Excel2007');
$objReader->setReadDataOnly(true);
$objPHPExcel= PHPExcel_IOFactory::load($document_folder."/".$file_name.".".$file_extension);
// $this->response($objPHPExcel);
$objPHPExcel=$objReader->load($document_folder."/".$file_name.".".$file_extension);
$totalrows=$objPHPExcel->setActiveSheetIndex(0)->getHighestRow();
$objWorksheet=$objPHPExcel->setActiveSheetIndex(0);
for($i=2;$i<=$totalrows;$i++){ //2 is one row after the header rows
$title= $objWorksheet->getCellByColumnAndRow(0,$i)->getValue();
$first_name= $objWorksheet->getCellByColumnAndRow(1,$i)->getValue();
$last_name= $objWorksheet->getCellByColumnAndRow(2,$i)->getValue();
$date_of_birth= $objWorksheet->getCellByColumnAndRow(3,$i)->getValue();
$email=$objWorksheet->getCellByColumnAndRow(4,$i)->getValue();
$phone_number=$objWorksheet->getCellByColumnAndRow(5,$i)->getValue();
$company=$objWorksheet->getCellByColumnAndRow(6,$i)->getValue();
$input=array(
'title'=>$title,
'first_name'=>$first_name,
'last_name'=>$last_name,
'date_of_birth'=>$date_of_birth,
'email'=>$email,
'phone_number'=>$phone_number,
'company'=>$company,
);
You have to remember that PHPExcel is just PHP, and so is CodeIgniter. You don't have to load PHPExcel through another library. If fact, it doesn't do anything for you. I put all of the PHPExcel files in /third_party/, and then do this:
require_once( APPPATH . 'third_party/PHPExcel-1.8/Classes/PHPExcel.php');
$objReader = PHPExcel_IOFactory::createReader('Excel2007');
Notice that in the example I am using v1.8
If you want to use $objReader in multiple methods, then just make it a class property. So $this->objReader instead.
I have a problem with calling PHPWord library in Code Igniter, I already using PHPExcel and there are no problems everything goes smoothly.
But I have a problem with this PHPWord, because when I tried to use the same method to call the PHPExcel, it doesnt solve anything. I still seeing an error.
It's not like I don't search it on the google, I already searched it, but still, no one can solve my problem, I don't where is the problem.
So let me explain what is the problem.
FYI: I using PHP 7.1.1
Because the PHP version, PHPWord got some errors that says a class named as a String that is known as variable, so because of that error, I changed it to Strings all of them that associated with that class.
After I changed it, I want to call the class with library file.
This is the file:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
require_once APPPATH.'/third_party/PHPWord/Autoloader.php';
use PhpOffice\PhpWord\Autoloader as Autoloader;
use PhpOffice\PhpWord\Settings as Settings;
use PhpOffice\PhpWord\PhpWord as PhpWord;
/* I tried two different ways */
// class Word extends PhpWord {
// public function __construct() {
// parent::__construct();
// }
// }
Autoloader::register();
Settings::loadConfig();
And this is the Controller code that calls the class.
$this->load->library('word');
$section = $this->word->createSection(array('orientation'=>'landscape'));
After I did that, it says Non-existent class: Word, I don't know anymore where is the problem, is it because I changed the class name? or it doesn't compatible with my CI version(3)?
Because I already tried different ways and still cannot solve this problem, can someone help me with this problem and show me what I did wrong? Thank you.
I haven't tried with PHP7 but I found this Github repo which worked for me.
https://github.com/webeasystep/phpword_codeigniter
I just copied the application\third_party\PhpWord folder and application\library\PhpWord.php into the same locations in my project and then used some of the code from the controller provided, e.g...
public function test()
{
$this->load->library('Phpword');
$phpWord = new \PhpOffice\PhpWord\PhpWord();
$phpWord->getCompatibility()->setOoxmlVersion(14);
$phpWord->getCompatibility()->setOoxmlVersion(15);
$filename = 'test.docx';
// add style settings for the title and paragraph
$section = $phpWord->addSection();
$section->addText("Hello, world");
$section->addTextBreak(1);
$section->addText("It's cold outside.");
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
$objWriter->save($filename);
// send results to browser to download
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.$filename);
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($filename));
flush();
readfile($filename);
unlink($filename); // deletes the temporary file
exit;
}
This works fine, I get a .docx when I hit my controller/test in a browser
Following library is working smoothly for me for PHP 7 version without any error.
https://github.com/rifqisucahyo/CI_PHPWord
class Word extends PHPWord {
public function __construct() {
parent::__construct();
$this->load->library('word');
}
function index() {
require_once APPPATH."/third_party/PHPWord.php";
$PHPWord = $this->word; // New Word Document
$section = $PHPWord->createSection(); // New portrait section
// Add text elements
$section->addText('Hello World!');
$section->addTextBreak(2);
$section->addText('Mohammad Rifqi Sucahyo.', array('name'=>'Verdana', 'color'=>'006699'));
$section->addTextBreak(2);
$PHPWord->addFontStyle('rStyle', array('bold'=>true, 'italic'=>true, 'size'=>16));
$PHPWord->addParagraphStyle('pStyle', array('align'=>'center', 'spaceAfter'=>100));
// Save File / Download (Download dialog, prompt user to save or simply open it)
$section->addText('Ini Adalah Demo PHPWord untuk CI', 'rStyle', 'pStyle');
$filename='just_some_random_name.docx'; //save our document as this file name
header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document'); //mime type
header('Content-Disposition: attachment;filename="'.$filename.'"'); //tell browser what's the file name
header('Cache-Control: max-age=0'); //no cache
$objWriter = PHPWord_IOFactory::createWriter($PHPWord, 'Word2007');
$objWriter->save('php://output');
}
}
I'm using Yii framework , and I have to load PHPExcel classes.
in my main.php I set the configuration as
'import'=>array(
'application.models.*',
'application.components.*',
'application.extensions.*',
'ext.PHPExcel.PHPExcel',
),
in I was edit the Register function inside Autoloader.php as follow
public static function Register() {
$functions = spl_autoload_functions();
foreach($functions as $function)
spl_autoload_unregister($function);
$functions=array_merge(array(array('PHPExcel_Autoloader', 'Load')), $functions);
foreach($functions as $function)
$x = spl_autoload_register($function);
return $x;
}
when I call $objPHPExcel =new PHPExcel(); it's working well,
but when I call $objDrawing = new PHPExcel_Worksheet_Drawing(); its return
include(PHPExcel_Worksheet_Drawing.php): failed to open stream: No such file or directory
my directory structure is :
extensions
-----PHPExcel
-------PHPExcel
------ PHPExcel.php
Thanks for help
Try this code out if it works, notice there are dual *
Yii::import('ext.PHPExcel.**', true);
$objDrawing = new PHPExcel_Worksheet_Drawing();
var_dump($objDrawing);
[Tested in Yii version: 1.1.13]
this module worked for me initially. but then I added Yii2 and spent a long time looking for a solution to the problem. for those who find this topic, as I did and also added Yii2 to Yii1, I will leave this solution.
for me first helped this.
spl_autoload_unregister(['YiiBase', 'autoload']);
require_once Yii::app()->params['rootPath'] . '/PHPExcel/Classes/PHPExcel.php';
spl_autoload_register(['YiiBase', 'autoload']);
when i added Yii2 i changed
spl_autoload_unregister(['Yii', 'autoload']);
spl_autoload_unregister(['YiiBase', 'autoload']);
require_once Yii::app()->params['rootPath'] . '/PHPExcel/Classes/PHPExcel.php';
spl_autoload_register(['YiiBase', 'autoload']);
spl_autoload_register(['Yii', 'autoload']);
and use
$objPHPExcel = new \PHPExcel();