set column name and column width using PHPExcel in codeigniter - codeigniter

Good day, I'm struggling to find out how to set a column name before each value in PHPExcel with codeigniter. Since my PHPExcel works to get the value from database, my problem is how to set a column name of each column.
current output image:
My code:
//load our new PHPExcel library
$this->load->library('excel');
//activate worksheet number 1
$this->excel->setActiveSheetIndex(0);
//name the worksheet
$this->excel->getActiveSheet()->setTitle('Users list');
// Trying to set a column name
$this->excel->getActiveSheet()->SetCellValue('A1', 'ID');
$this->excel->getActiveSheet()->SetCellValue('B1', 'FIRST NAME');
$this->excel->getActiveSheet()->SetCellValue('C1', 'LAST NAME');
$this->excel->getActiveSheet()->SetCellValue('D1', 'EMAIL');
$this->excel->getActiveSheet()->SetCellValue('E1', 'TIME');
// get all users in array formate
$users = $this->User_info->getallusers();
// read data to active sheet
$this->excel->getActiveSheet()->fromArray($users);
$filename='just_some_random_name.xlsx'; //save our workbook as this file name
header('Content-Type: application/vnd.ms-excel'); //mime type
header('Content-Disposition: attachment;filename="'.$filename.'"'); //tell browser what's the file name
header('Cache-Control: max-age=0'); //no cache
//save it to Excel5 format (excel 2003 .XLS file), change this to 'Excel2007' (and adjust the filename extension, also the header mime type)
//if you want to save it as .XLSX Excel 2007 format
$objWriter = PHPExcel_IOFactory::createWriter($this->excel, 'Excel2007');
//force user to download the Excel file without writing it to server's HD
ob_end_clean();
$objWriter->save('php://output');
I want the output look like this
One more problem that I've seen is the width of every column. can you fix it also for me?

$this->excel->getActiveSheet()->fromArray($users);
The default top-left cell for the fromArray() method is cell A1, and it will overwrite anything that is already in cell A1.... if you want to avoid overwriting the headers that you have already set in row 1, then you'll need to tell fromArray() to start at row 2, so the top-left cell will be A2
$this->excel->getActiveSheet()->fromArray($users, null, 'A2');

You can try this solution for export excel.
//load our new PHPExcel library
$this->load->library('excel');
//activate worksheet number 1
$this->excel->setActiveSheetIndex(0);
//name the worksheet
$this->excel->getActiveSheet()->setTitle('Users list');
$this->excel->getActiveSheet()->getColumnDimension('A')->setAutoSize(true);
$this->excel->getActiveSheet()->getColumnDimension('B')->setAutoSize(true);
$this->excel->getActiveSheet()->getColumnDimension('C')->setAutoSize(true);
$this->excel->getActiveSheet()->getColumnDimension('D')->setAutoSize(true);
$this->excel->getActiveSheet()->getColumnDimension('E')->setAutoSize(true);
$this->excel->getActiveSheet()->getStyle("A1:E1")->applyFromArray(array("font" => array("bold" => true)));
$this->excel->setActiveSheetIndex(0)->setCellValue('A1', 'ID');
$this->excel->setActiveSheetIndex(0)->setCellValue('B1', 'FIRST NAME');
$this->excel->setActiveSheetIndex(0)->setCellValue('C1', 'LAST NAME');
$this->excel->setActiveSheetIndex(0)->setCellValue('D1', 'EMAIL ADDRESS');
$this->excel->setActiveSheetIndex(0)->setCellValue('E1', 'TIME');
// get all users in array formate
$this->excel->getActiveSheet()->fromArray($users, null, 'A2');
// read data to active sheet
$this->excel->getActiveSheet()->fromArray($users);
$filename='just_some_random_name.xlsx'; //save our workbook as this file name
header('Content-Type: application/vnd.ms-excel'); //mime type
header('Content-Disposition: attachment;filename="'.$filename.'"'); //tell browser what's the file name
header('Cache-Control: max-age=0'); //no cache
//save it to Excel5 format (excel 2003 .XLS file), change this to 'Excel2007' (and adjust the filename extension, also the header mime type)
//if you want to save it as .XLSX Excel 2007 format
$objWriter = PHPExcel_IOFactory::createWriter($this->excel, 'Excel2007');
//force user to download the Excel file without writing it to server's HD
ob_end_clean();
$objWriter->save('php://output');
you can add more style for heading column using applyFromArray.

Related

Converting html to pdf after clicking on download button in codeigniter

I have created a resume builder application.User enters all required details and i am storing all details in database. Then i am fetching those records and displaying it in different templates. I have created 3 templates. Now I want to give download as pdf and download as docx two download buttons. Once user clicks on any of buttons file will be downloaded in their chosen format. Either pdf or docx.
Is it possible to achieve in codeigniter?
i used Tcpdf
Controller Code is
the code written in controller download $this - > load - > library("Pdf");
// create new PDF document
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
// set auto page breaks
$pdf - > SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
// set image scale factor
$pdf - > setImageScale(PDF_IMAGE_SCALE_RATIO);
// Add a page
// This method has several options, check the source code documentation for more information.
$pdf - > AddPage();
// Set some content to print
$html = $this - > load - > view('resume/res_template1_view', array('left_sidebar' => 'sidebar/left_sidebar', ' right_sidebar' => 'sidebar/right_sidebar'), $data, TRUE);
// Print text using writeHTMLCell()
$pdf - > writeHTML($html, 0, 0, '', '', 0, 1, 0, true, '', true);
//$pdf->writeHTML($html, true, false, true, false, '');
// Close and output PDF document
// This method has several options, check the source code documentation for more information.
$pdf - > Output('resume.pdf', 'D');
Probably you need to use some library in CI to achieve this. Please check below.
you can use Html2Pdf for CI3 library. https://github.com/shyamshingadiya/HTML2PDF-CI3
How to Use
There are 4 options you a required to set in order to create a PDF; folder, filename, paper and HTML
//Load the library
$this->load->library('html2pdf');
//Set folder to save PDF to
$this->html2pdf->folder('./assets/pdfs/');
//Set the filename to save/download as
$this->html2pdf->filename('test.pdf');
//Set the paper defaults
$this->html2pdf->paper('a4', 'portrait');
//Load html view
$this->html2pdf->html(<h1>Some Title</h1><p>Some content in here</p>);
The create function has two options 'save' and 'download'. Save will just write the PDF to the folder you choose in the settings. Download will force the PDF to download in the clients browser.
//Create the PDF
$this->html2pdf->create('save');
Advanced usage
Theres no reason why you can't build and pass a view to the html() function. Also note the create() function will return the saved path if you choose the 'save' option.
$data = array(
'title' => 'PDF Created',
'message' => 'Hello World!'
);
//Load html view
$this->html2pdf->html($this->load->view('pdf', $data, true));
if($path = $this->html2pdf->create('save')) {
//PDF was successfully saved or downloaded
echo 'PDF saved to: ' . $path;
}
Please check above mentioned solution. Let me know if it not works.

PHPExcel style text to center

I'm using PHPExcel with codeigniter to generate .xlx, .xlxs file, Every thing is working perfect except text formatting. Here is the screenshot of html view that I'm passing to PHPExcel library to generate .xlx file.
And Here is the output.
As you can see that text indentation and styles are removed. Here is my code used to generate output.
public function html_to_excel_download($filename, $data=null){
if ($data != null) {
// proper encoding of data UTF-8 for unicode characters
$data = chr(255).chr(254).iconv("UTF-8", "UTF-16LE//IGNORE", $data);
// Put the data into a temporary file
$tmpfile = time().'.html';
file_put_contents($tmpfile, $data);
// Read the contents of the file into PHPExcel Reader class
$reader = new PHPExcel_Reader_HTML;
$content = $reader->load($tmpfile);
// Excel Writer
$objWriter = PHPExcel_IOFactory::createWriter($content, 'Excel2007');
// Download File
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="'.$filename.'"');
header('Cache-Control: max-age=0');
$objWriter->save('php://output');
unlink($tmpfile);
exit();
}
}
How can I indent title text to center?
you may try another way to do that...
Step 1) Define "$this->excel->setActiveSheetIndex(0);" at the top of function
step 2) Define style array and add it as a variable with excel object like,
$styleArray = array(
'font' => array(
'bold' => true,
'color' => array('rgb' => '2F4F4F')
),
'alignment' => array(
'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
)
);
Step 3) $this->excel->getActiveSheet()->getStyle('A3:Z3')->applyFromArray($styleArray);
Note: You have to use getStyle() in your code to apply specific styles on column/row
// single column A, setting e.g. horizontal alignment
$objWorksheet->getStyle('A')->getAlignment()->setHorizontal(...);
// range of columns A to K
$objWorksheet->getStyle('A:K')->getAlignment()->setHorizontal(...);
AND you can see full documentation on this site for formatting SHEET
HERE
There are two ways you can get rid of this issue, one is without json array:
$doc->getActiveSheet()->getStyle('A1:H1')->getAlignment()
->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
where $doc = new PHPExcel(); or a PHPExcel object
The second is using the json array as described here
I'm pretty confident that you'll find all instructions about this library in the official documentation

PHPExcel - Create spreadsheet from HTML table?

I'm trying to create a simple reporting system, which can output either HTML or export to Excel. I have got it to create a HTML table successfully through a Codeigniter view but I want to know if there's any way I can re-use that view to create the Excel export, rather than doing it manually, as I'll then have to update it in two places every time I want to make a change to the report.
Any advice appreciated.
Thanks.
This seems to be working:
// Load the table view into a variable
$html = $this->load->view('table_view', $data, true);
// Put the html into a temporary file
$tmpfile = time().'.html';
file_put_contents($tmpfile, $html);
// Read the contents of the file into PHPExcel Reader class
$reader = new PHPExcel_Reader_HTML;
$content = $reader->load($tmpfile);
// Pass to writer and output as needed
$objWriter = PHPExcel_IOFactory::createWriter($content, 'Excel2007');
$objWriter->save('excelfile.xlsx');
// Delete temporary file
unlink($tmpfile);

PHPWord_Template save to client

I have download the package PHPWord_0.6.2_Beta.zip from this siteThere are 2 directory : Examples and PHPWord, and 1 file : PHPWord.phpI put PHPWord directory and PHPWord.php in application/third_party and create new library named 'Word.php' in application/libraries as explained in this articleHere is the new library code Word.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
require_once APPPATH."/third_party/PHPWord.php";
class Word extends PHPWord {
public function __construct() {
parent::__construct();
}
}
?>
Now we can easily use PHPWord as CI libraryI have tried Text Example from directory Example in downloaded package, here is the original code
<?php
require_once '../PHPWord.php';
// New Word Document
$PHPWord = new PHPWord();
// New portrait section
$section = $PHPWord->createSection();
// Add text elements
$section->addText('Hello World!');
$section->addTextBreak(2);
$section->addText('I am inline styled.', 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));
$section->addText('I am styled by two style definitions.', 'rStyle', 'pStyle');
$section->addText('I have only a paragraph style definition.', null, 'pStyle');
// Save File
$objWriter = PHPWord_IOFactory::createWriter($PHPWord, 'Word2007');
$objWriter->save('Text.docx');
?>
And I tried implement it in my CI controller, here is the code PHPWord_Text.php
<?php if (!defined('BASEPATH')) exit ('No direct script access allowed');
class PHPWord_Text extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->library('word');
}
function index() {
$PHPWord = $this->word; // New Word Document
$section = $PHPWord->createSection(); // New portrait section
// Add text elements
$section->addText('Hello World!');
$section->addTextBreak(2);
$section->addText('I am inline styled.', 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));
$section->addText('I am styled by two style definitions.', 'rStyle', 'pStyle');
$section->addText('I have only a paragraph style definition.', null, 'pStyle');
// Save File / Download (Download dialog, prompt user to save or simply open it)
$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');
}
}
?>
Access it in
http://localhost/codeigniter/index.php/PHPWord_Text
Foilaa!!! my code works! But... I'm a bit confused when i tried to translate Template Example in directory Examples from downloaded package into a new CI controller, here is the original code of Template.php
<?php
require_once '../PHPWord.php';
$PHPWord = new PHPWord();
$document = $PHPWord->loadTemplate('Template.docx');
$document->setValue('Value1', 'Sun');
$document->setValue('Value2', 'Mercury');
$document->setValue('Value3', 'Venus');
$document->setValue('Value4', 'Earth');
$document->setValue('Value5', 'Mars');
$document->setValue('Value6', 'Jupiter');
$document->setValue('Value7', 'Saturn');
$document->setValue('Value8', 'Uranus');
$document->setValue('Value9', 'Neptun');
$document->setValue('Value10', 'Pluto');
$document->setValue('weekday', date('l'));
$document->setValue('time', date('H:i'));
$document->save('Solarsystem.docx');
?>
Can anyone please help me with this problem? please.. T_TNOTE : i dont want it to be saved in server, i want it to show download dialog prompt user wether to save it or open it, works like some code down here
// Save File / Download (Download dialog, prompt user to save or simply open it)
$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 think you may be experiencing more than one issue with Template.php.
First, you may be trying to figure out what it is doing.
With the other examples x.php produces x.docx. In the case of Template.php, it uses Template.docx to produce Solarsystem.docx.
The variables Value1, Value2, Value3, etc. are all defined within Template.docx as ${Value1}, ${Value2}, ${Value3}, etc. If you change the values on the right in Template.php, it will change the corresponding values in Solarsystem.docx.
Second, you seem to be concerned with output.
What works for me is this:
$filename = 'nameOfFile.docx';
$document->save($filename);
header('Content-Description: File Transfer');
header('Content-type: application/force-download');
header('Content-Disposition: attachment; filename='.basename($filename));
header('Content-Transfer-Encoding: binary');
header('Content-Length: '.filesize($filename));
readfile($filename);
This way still saves it on the server but downloads it too. If I use both $document->save(); and $objWriter->save(); I get a blank document when I try to use readfile(); on the file saved by objWriter.
I thing this is correct :
$filename = 'nameOfFile.docx';
$document->save($filename);
header('Content-Description: File Transfer');
header('Content-type: application/force-download');
header('Content-Disposition: attachment; filename='.basename($filename));
header('Content-Transfer-Encoding: binary');
header('Content-Length: '.filesize($filename));
readfile($filename);
unlink($filename);
Method save() of Template class returns name of temp file document, so you just give it to user with readfile($tempName);
I'm not sure I get your question correctly, so excuse me if I'm wrong.
In your 4th code block you've got a line
$document->save('Solarsystem.docx');
If you don't want to save the file to the local disk, but instead send it to the client, you'll just have to remove that line and add the code from the 5th code block:
// Save File / Download (Download dialog, prompt user to save or simply open it)
$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');
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
require_once APPPATH . '/src/PhpWord/Autoloader.php';
use PhpOffice\PhpWord\Autoloader as Autoloader;
Autoloader::register();

Joomla TinyMCE editor do not save inserted image

We are building joomla component. And we use joomla editor in which we insert content.
But there is a problem, because when we add image to editor and save it, it do not add image to database and when we opening this element to edit it again, there is only text in editor, image disappears.
This is how we use it:
$editor =& JFactory::getEditor();
echo $editor->display('text', $this->hello->text, '800', '300', '20', '20');
Maybe there is need to supply aditional parameters to display method?
Problem solved.
The standard way of getting the form data $post = JRequest::get('post'); is not enough in the case of using a editor. This will filter the content, hence losing line breaks and paragraps. So we need to add an extra line to get the editor contents in a raw unfiltered way. This data will be passed to the model to save into the database.
To get HTML form post data you need to get this data in following way
$data = JRequest::getVar( 'editorName', 'defaultValue', 'post', 'string', JREQUEST_ALLOWRAW );
And need to add a javascript for the view(tmpl file)
function submitbutton(action) {
var form = document.adminForm;
switch(action)
{
case 'save':case 'apply':
<?php
$editor =& JFactory::getEditor();
echo $editor->save( 'editorName' );
?>
case 'publish':
case 'unpublish':
case 'cancel':
default:
submitform( action );
}
}

Resources