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.
Related
I'm using PHPSpreadsheet to create Excel.
I want t generate the Excel file, then convert the Excel file in a PDF one.
So I've done the following :
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Writer\Pdf\Mpdf;
use PhpOffice\PhpSpreadsheet\Reader\Exception;
class DevisGenerator
{
public function runDevis()
{
$spreadsheet = $this->loadexcelTemplate();
$uuid = $this->uniqidReal();
$filename = $this->writeName($spreadsheet, $uuid);
$this->convertPdf($spreadsheet, $filename);
}
public function writeName($spreadsheet, $uuid)
{
$worksheet = $spreadsheet->getActiveSheet();
$worksheet->getCell('B2')->setValue('Toto');
try {
$writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
$filename = $uuid;
$writer->save($filename.'.xlsx');
}catch (Exception $e)
{
//TODO gestion erreur
}
return $filename;
}
public function convertPdf($spreadsheet, $filename)
{
$writer = new \PhpOffice\PhpSpreadsheet\Writer\Pdf\Mpdf($spreadsheet);
$writer->save($filename.'.pdf');
}
But whan I run the code the following error appear :
Attempted to load class "Mpdf" from namespace "Mpdf".
Did you forget a "use" statement for "PhpOffice\PhpSpreadsheet\Writer\Pdf\Mpdf"?
I did not understand this error, I have correctly insert the use statement in my code.
Any idea ?
I've already got a similar issue with Mpdf.
PHPSpreadsheet supports multiple Librairies to generate PDF.
I'm nut using Mpdf but Tcpdf.
I'm also not sure but you need to install them manually.
composer require tecnickcom/tcpdf
Then in your code :
$writer = new Tcpdf($spreadsheet);
And don't forget the use statement ;)
Hope this help !
After use statement before class, you should use only:
public function convertPdf($spreadsheet, $filename)
{
$writer = new Mpdf($spreadsheet);
$writer->save($filename.'.pdf');
}
Since you use the fully qualified namespace when creating the instance, the use statement is not taken into account (thus the error message).
It seems like you have added a supplementary slash at the beginning of the namespace when creating your Mpdf instance, removing it will solve your issue.
$writer = new PhpOffice\PhpSpreadsheet\Writer\Pdf\Mpdf($spreadsheet);
But since you have added a use statement, you do not need to use the fully qualified namespace again, you can do
$writer = new Mpdf($spreadsheet);
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 am using PHPSpreadsheet now, I am trying to get rows to auto height. It is working fine in MSOffice But Not work in LibreOffice.
Question How to make the row auto height work in LibreOffice latest version. Works fine in MSOffice.
Autoheight
$spreadsheet->getActiveSheet()->getRowDimension(1)->setRowHeight(-1);
foreach($spreadsheet->getActiveSheet()->getRowDimensions() as $rowID) {
$rowID->setRowHeight(-1);
}
Controller
<?php
require(APPPATH . 'vendor/autoload.php');
use PhpOffice\PhpSpreadsheet\Spreadsheet;
class Events extends MX_Controller {
public function test() {
$spreadsheet = new Spreadsheet();
$spreadsheet->getProperties()->setCreator('')
->setLastModifiedBy('')
->setTitle('')
->setSubject('')
->setDescription('');
$spreadsheet->getDefaultStyle()->getFont()->setName('Arial');
$spreadsheet->getDefaultStyle()->getFont()->setSize(24);
foreach(range('A','B') as $columnID) {
$spreadsheet->getActiveSheet()->getColumnDimension($columnID)->setAutoSize(true);
}
$spreadsheet->getActiveSheet()->getStyle('A')->getAlignment()->setWrapText(true);
$spreadsheet->getActiveSheet()->getRowDimension(1)->setRowHeight(-1);
foreach($spreadsheet->getActiveSheet()->getRowDimensions() as $rowID) {
$rowID->setRowHeight(-1);
}
$spreadsheet->setActiveSheetIndex(0)
->setCellValue("A1",'Firstname')
->setCellValue("B1",'Lastname')
->setCellValue("A2",'John')
->setCellValue("B2",'Doe');
$spreadsheet->getActiveSheet()->setTitle('Users Information');
$spreadsheet->setActiveSheetIndex(0);
/* Here there will be some code where you create $spreadsheet */
// redirect output to client browser
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="myfile.xls"');
header('Cache-Control: max-age=0');
$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xls');
$writer->save('php://output');
exit;
}
}
Try the following code
$spreadsheet->getActiveSheet()->getStyle('A1:D4')
->getAlignment()->setWrapText(true);
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');
}
}
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'));