PHPExcel Error when opening outputted Excel file - export-to-excel

I hope I'm in the right place. I have this PHP that exports data from SQL to XLSX.
<?php
$conexion=odbc_connect("syb_master","sa","server");
$sql = "Here's the query";
$exec = odbc_exec($conexion,$sql);
$resultado = odbc_result_all($exec);
$registros = odbc_num_rows ($resultado);
require_once '../Classes/PHPExcel.php';
if ($registros > 0) {
$objPHPExcel = new PHPExcel();
//Informacion del excel
$objPHPExcel->
getProperties()
->setCreator("ingenieroweb.com.co")
->setLastModifiedBy("ingenieroweb.com.co")
->setTitle("Exportar excel desde mysql")
->setSubject("Ejemplo 1")
->setDescription("Documento generado con PHPExcel")
->setKeywords("ingenieroweb.com.co con phpexcel")
->setCategory("ciudades");
$i = 1;
while ($registro = odbc_fetch_object ($resultado)) {
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A'.$i, $registro->name);
$i++;
}
$objPHPExcel->getActiveSheet()->setTitle('Simple');
}
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="ejemplo1.xlsx"');
header('Cache-Control: max-age=0');
$objWriter=PHPExcel_IOFactory::createWriter($objPHPExcel,'Excel2007');
$objWriter->save('php://output');
exit;
odbc_close($conexion);
?>
It works when exporting to XLS, but when I export to XLS, everything seems to be correct except for the fact that when done, excel can't open the file. It gives the error: "Excel can't open the file because the file format or file extension is not valid."
I think it's because the query has a lot of data, but I'm not sure. I'm new to phpexcel. I hope you can help me. Thanks!

This is my code. It not so good, but i have no such problem:
/** Error reporting */
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
date_default_timezone_set('Europe/London');
define('EOL',(PHP_SAPI == 'cli') ? PHP_EOL : '<br />');
/** Include PHPExcel */
require_once 'Classes/PHPExcel.php';
// Create new PHPExcel object
//echo date('H:i:s') , " Create new PHPExcel object" , EOL;
$objPHPExcel = new PHPExcel();
// Rename worksheet
$objPHPExcel->getActiveSheet()->setTitle('Simple');
$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(50);
$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(50);
$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(50);
$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(50);
$objPHPExcel->getProperties()->setCreator("Ketov Alexandr")
->setLastModifiedBy("Ketov Alexandr")
->setTitle("PHPExcel Test Document")
->setSubject("PHPExcel Test Document")
->setDescription("Test document for PHPExcel, generated using PHP classes.")
->setKeywords("office PHPExcel php")
->setCategory("Test result file");
//$objPHPExcel->getActiveSheet()->getRowDimension(1)->setRowHeight(-1);
$query = "SELECT * FROM `lang`";
$result = mysql_query($query) or die(mysql_error());
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A1', 'Ключ')
->setCellValue('B1', 'На русском')
->setCellValue('C1', 'На казахском')
->setCellValue('D1', 'Портлет');
$styleArray = array(
'font' => array(
'bold' => true,
'color' => array('rgb' => '000000'),
'size' => 11,
'name' => 'Verdana'
));
$objPHPExcel->getActiveSheet()->getStyle('A1')->applyFromArray($styleArray)->getBorders()->getAllBorders()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
$objPHPExcel->getActiveSheet()->getStyle('B1')->applyFromArray($styleArray)->getBorders()->getAllBorders()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
$objPHPExcel->getActiveSheet()->getStyle('C1')->applyFromArray($styleArray)->getBorders()->getAllBorders()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
$objPHPExcel->getActiveSheet()->getStyle('D1')->applyFromArray($styleArray)->getBorders()->getAllBorders()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
$n = 2;
while ($row = mysql_fetch_object($result))
{
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A'.$n, $row->id)
->setCellValue('B'.$n, $row->ru)
->setCellValue('C'.$n, $row->kz)
->setCellValue('D'.$n, $row->module);
$objPHPExcel->getActiveSheet()->getStyle('A'.$n)->getBorders()->getAllBorders()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
$objPHPExcel->getActiveSheet()->getStyle('B'.$n)->getBorders()->getAllBorders()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
$objPHPExcel->getActiveSheet()->getStyle('C'.$n)->getBorders()->getAllBorders()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
$objPHPExcel->getActiveSheet()->getStyle('D'.$n)->getBorders()->getAllBorders()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
$n++;
}
// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$objPHPExcel->setActiveSheetIndex(0);
// Redirect output to a client’s web browser (Excel5)
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;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;

Related

Not able to save generated pdf on my remote server

I am trying to save generated pdf in custom folder but its not saving. I want to pdf to send as attachment in email
Here is my code generate and save pdf
public function email($timestamp=0, $load_id=0, $type=0){
$this->load->library('tcpdf/Pdf');
$pdf = new Pdf('P', 'mm', 'LETTER', true, 'UTF-8', false);
$pdf->SetTitle('Document');
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);
$pdf->SetHeaderMargin(10);
$pdf->SetLeftMargin(10);
$pdf->SetRightMargin(10);
$pdf->SetTopMargin(10);
$pdf->SetAutoPageBreak(true, 25);
$pdf->SetAuthor('Author');
$pdf->SetDisplayMode('real', 'default');
$pdf->Write(5, 'Cal Sierra Load Document'); // add a page
$pdf->AddPage();
// $carriers = $this->admin_model->getCarriers(array(), array(), 0,0,1,"","","",1);
$load=$this->admin_model->getLoad($load_id);
$pickupDrops=$this->admin_model->getPickupDrops(0,0,1,0,$load_id);
$loadPickups=array();
$loadDrops=array();
if(!empty($pickupDrops)){
foreach($pickupDrops as $row){
if($row['type']==1)
$loadPickups[]=$row;
else
$loadDrops[]=$row;
}
}
$data['load'] = $load;
$data['loadPickups'] = $loadPickups;
$data['loadDrops'] = $loadDrops;
// $data['carriers'] = $carriers;
$data['settings'] = $this->settings_model->getSettingsFile();
$data['currentTime'] = $timestamp;
// echo "<pre>";
// print_r($data);
// exit();
switch ($type) {
case 1:
$html = $this->load->view('documents/doc1', $data, true);
break;
case 2:
$html = $this->load->view('documents/doc2', $data, true);
break;
case 3:
$html = $this->load->view('documents/doc3', $data, true);
break;
default:
}
$pdf->Output('custom'.'Document.pdf', 'F');
$this->Output("custom");
exit();
}
I am not sure where put my folder to pdf i am also adding my folder layout picture https://i.stack.imgur.com/tUadw.png
Try adding a more complete path to the output function. Something like:
$pdf->output(FCPATH . "my/directory/path/" . "pdfName.pdf", 'F');

phpspreadsheet working on local but not on live

I installed phpspreadsheet with composer in my Codeigniter project. It's working fine on local but throwing an error on the live environment:
This site can’t be reached The webpage at
http://www.xxxxxx.com/email/exportemail might be temporarily down or
it may have moved permanently to a new web address.
ERR_INVALID_RESPONSE
My code:
require(APPPATH . 'vendor/autoload.php');
use PhpOffice\PhpSpreadsheet\Helper\Sample;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
class Email extends CI_Controller {
public function __construct() {
parent::__construct();
}
public function exportemail(){
$customers = $this->sales_model->getCustomerRows();
$spreadsheet = new Spreadsheet();
$spreadsheet->setActiveSheetIndex(0)
->setTitle('Location')
->setCellValue('A1', 'Customer')
->setCellValue('B1', 'Contact name')
->setCellValue('C1', 'Managed by')
->setCellValue('D1', 'Email');
foreach($customers as $key => $customers_data) {
$x = $key + 2;
$spreadsheet->setActiveSheetIndex(0)
->setCellValue("A$x", $customers_data['cust_pub'])
->setCellValue("B$x", $customers_data['ccd_name'])
->setCellValue("C$x", $customers_data['m_name'])
->setCellValue("D$x", $customers_data['cust_pub_email']);
}
$filename = 'Export_Email.xlsx'; //save our workbook as this file name
// Redirect output to a client’s web browser (Xlsx)
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="'.$filename.'"');
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
$writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save('php://output');
}
}
Can anyone tell me what changes need to be made on live?

How to export mysql table to csv or excel file using phpExcel in CODEIGNITER

I've been searching on how to export mysql table to csv or excel file. I've seen some steps and I followed them. Is there a way on how to export the mysql table to csv or excel file using codeigniter?
I've tried this PHPExcel. But it seems not working to me.
function index()
{
$query = $this->db->get('filter_result');
if(!$query)
return false;
// Starting the PHPExcel library
$this->load->library('PHPExcel');
$this->load->library('PHPExcel/IOFactory');
$objPHPExcel = new PHPExcel();
$objPHPExcel->getProperties()->setTitle("export")->setDescription("none");
$objPHPExcel->setActiveSheetIndex(0);
// Field names in the first row
$fields = $query->list_fields();
$col = 0;
foreach ($fields as $field)
{
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, 1, $field);
$col++;
}
// Fetching the table data
$row = 2;
foreach($query->result() as $data)
{
$col = 0;
foreach ($fields as $field)
{
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $data->$field);
$col++;
}
$row++;
}
$objPHPExcel->setActiveSheetIndex(0);
$objWriter = IOFactory::createWriter($objPHPExcel, 'Excel5');
// Sending headers to force the user to download the file
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="Products_'.date('dMy').'.xls"');
header('Cache-Control: max-age=0');
$objWriter->save('php://output');
}
Here is a code I use.
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class excel{
function to_excel($array, $filename) {
header('Content-Disposition: attachment; filename='.$filename.'.xls');
header('Content-type: application/force-download');
header('Content-Transfer-Encoding: binary');
header('Pragma: public');
print "\xEF\xBB\xBF"; // UTF-8 BOM
$h = array();
foreach($array->result_array() as $row){
foreach($row as $key=>$val){
if(!in_array($key, $h)){
$h[] = $key;
}
}
}
echo '<table><tr>';
foreach($h as $key) {
$key = ucwords($key);
echo '<th>'.$key.'</th>';
}
echo '</tr>';
foreach($array->result_array() as $row){
echo '<tr>';
foreach($row as $val)
$this->writeRow($val);
}
echo '</tr>';
echo '</table>';
}
function writeRow($val) {
echo '<td>'.$val.'</td>';
}
}
?>
Create a library with this code and call it as:
public function brandExcel() {
$this->load->library('excel');
$result = $this->config_model->getBrandsForExcel();
$this->excel->to_excel($result, 'brands-excel');
}
efenacigiray's answer was great but i got a weird error as the xls is in different format than specified so i just made another function and it works great.
class excel {
function create_excel($array) {
// Create new PHPExcel object
$objPHPExcel = new PHPExcel();
// Set document properties
$objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
->setLastModifiedBy("Maarten Balliauw")
->setTitle("Office 2007 XLSX Test Document")
->setSubject("Office 2007 XLSX Test Document")
->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
->setKeywords("office 2007 openxml php")
->setCategory("Test result file");
//'id,name,contact_name,email,email2,mobile,mobile2,website,country,city,address,postal_code,info'
// Add some data
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A1', 'Id')
->setCellValue('B1', 'name!')
->setCellValue('C1', 'contact_name')
->setCellValue('D1', 'email')
->setCellValue('K1', 'address')
->setCellValue('L1', 'postal_code');
$i = 2;
foreach($array as $row){
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A'.$i, $row['id'])
->setCellValue('B'.$i, $row['name'])
->setCellValue('C'.$i, $row['contact_name'])
->setCellValue('D'.$i, $row['email'])
->setCellValue('K'.$i, $row['address'])
->setCellValue('L'.$i, $row['postal_code']);
$i++;
}
// Miscellaneous glyphs, UTF-8
// $objPHPExcel->setActiveSheetIndex(0)
// ->setCellValue('A4', 'Miscellaneous glyphs')
// ->setCellValue('A5', 'éàèùâêîôûëïüÿäöüç');
// Rename worksheet
$objPHPExcel->getActiveSheet()->setTitle('Probable Clients');
// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$objPHPExcel->setActiveSheetIndex(0);
// Redirect output to a client’s web browser (Excel5)
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="probClients.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');
}
}
I found efenacigiray's code worked for me too, but I had to remove the code '->result_array()'
Using code igniter version: 2.1.4
(Would have wrote this as a comment, but I don't have enough rep yet)
for me.
print "\xEF\xBB\xBF"; // UTF-8 BOM <- this line cuased an error
delete this line and use
echo '<meta http-equiv="content-type" content="application/xhtml+xml; charset=UTF-8" />';
this meta tag instead.
Thanks to efenacigiray

Kohana 3.2 + PHPExcel creates empty document when there are more than 31 rows written.

I'm trying to create a simple excel document that contains a 3-column list. (First Name, Last Name, Email Address)
When I output more than 31 rows, a blank excel file is created. Does anyone know how to fix it?
My code below:
$guests = ORM::factory('guest')
->order_by('last_name', 'ASC')
->find_all()
->as_array();
$columns = array('first_name', 'last_name', 'email');
$objPHPExcel = new PHPExcel();
$objPHPExcel->getProperties()
->setCreator('Me')
->setLastModifiedBy('Me)
->setTitle('Guest List')
->setSubject('Guest List')
->setDescription('Title of Report, run on ' . date('m/d/Y H:i:s'));
$objPHPExcel->createSheet(0);
$objPHPExcel->setActiveSheetIndex(0);
foreach($guests as $row => $guest) {
$source = array();
$column = 0;
$next_row = $objPHPExcel->getActiveSheet()->getHighestRow();
foreach($guest->as_array() as $column_name => $data) {
if(in_array($column_name, $columns)) {
$objPHPExcel->getActiveSheet()
->setCellValueByColumnAndRow($column, $next_row+1, $data);
$column++;
// unset($data);
}
}
}
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$this->response->body($objWriter->save('php://output'));
$this->response->send_file(TRUE, 'GuestList.xls');
Kohana has a hard time handling the rendered file using the send_file() method, so write the file to disk using the built-in method from PHPExcel. Then use Kohana to deliver the saved file as a download.
$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
$objWriter->save($filename, 'EXCEL2007');
$this->response->send_file( DOCROOT.$filename );

using phpexcel in codeigniter

i am using the phpexcel library to export my report to excel file.
but i want to have my own excel file and use it with phpexcel.
here is the code i used:
public function event_reportexcel($id)
{
$this->load->library('excel');
$this->excel->setActiveSheetIndex(0);
$this->excel->getActiveSheet()->setTitle('test worksheet');
$this->excel->getActiveSheet()->setCellValue('A1', 'This is just some text value');
$this->excel->getActiveSheet()->getStyle('A1')->getFont()->setSize(20);
$this->excel->getActiveSheet()->getStyle('A1')->getFont()->setBold(true);
$this->excel->getActiveSheet()->mergeCells('A1:D1');
$this->excel->getActiveSheet()->getStyle('A1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
$filename='just_some_random_name.xls'; //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
$objWriter = PHPExcel_IOFactory::createWriter($this->excel, 'Excel5');
//force user to download the Excel file without writing it to server's HD
$objWriter->save('php://output');
}
it will put my data in a new excel file, but i need this function to use a excel file as template.
You can open the file and edit it as you need then save it
$fileType = 'Excel5';
$fileName = 'testFile.xls';
// Read the file
$objReader = PHPExcel_IOFactory::createReader($fileType);
$objPHPExcel = $objReader->load($fileName);
// Change the file
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A1', 'Hello')
->setCellValue('B1', 'World!');
// Write the file
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, $fileType);
$objWriter->save($fileName);
You can see this post for more details.
THis will help u
public function export(){
$this->load->model('authors_model');
$this->load->library('excel');
$object = new PHPExcel();
$object->setActiveSheetIndex(0);
$table_columns = array('ID','first_name','last_name','Email','BirthDate','Added');
$column = 1;
foreach ($table_columns as $dd) {
$object->getActiveSheet()->setCellValueByColumnAndRow($column,1, $dd);
$column++;
}
$employee_data = $this->authors_model->get_all_data();
$row_no = 2 ;
foreach ($employee_data as $value) {
$object->getActiveSheet()->setCellValueByColumnAndRow(0 ,$row_no,$value->id );
$object->getActiveSheet()->setCellValueByColumnAndRow(1 ,$row_no,$value->first_name );
$object->getActiveSheet()->setCellValueByColumnAndRow(2 ,$row_no,$value->last_name );
$object->getActiveSheet()->setCellValueByColumnAndRow(3 ,$row_no,$value->email );
$object->getActiveSheet()->setCellValueByColumnAndRow(4 ,$row_no,$value->birthdate );
$object->getActiveSheet()->setCellValueByColumnAndRow(5 ,$row_no,$value->added );
$row_no++;
}
ob_end_clean();
header('Content-Type: application/vnd.ms-excel'); //mime type
header("Content-Disposition: attachment; filename=\"filename.xls\"");
header("Cache-Control: max-age=0");
$objWriter = PHPExcel_IOFactory::createWriter($object, 'Excel5');
$objWriter->save('php://output');
}

Resources