PHPExcel error when opening created File in EXCEL - php

I create with a php-script which uses the PHPExcel Library an simple .xlsx file. But when I want to open it in MS Excel 2010 on Win7, I get an error message that file format is wrong or the file is damaged. Tried several possible solutions from the internet but nothing worked for me.
public function createControllingFile($suffix){
$this->PHPExcel = new PHPExcel();
$year = date('y');
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Cache-Control: max-age=0');
$this->objWriter = PHPExcel_IOFactory::createWriter($this->PHPExcel, 'excel5');
$this->objWriter->save('tmp/controlling_'.$year.'_'.$suffix.'.xlsx');
$_SESSION['counter'] = 0;
exit();
}
Hope you can help me, the session thing is to count up something

$this->objWriter->save('tmp/controlling_'.$year.'_'.$suffix.'.xlsx');
saves to a file on your servers filesystem, and nothing is sent to the client browser.
If you want to send to the client's browser, change that line to:
$this->objWriter->save('php://output');
just like in 01simple-download-xlsx.php in the /Tests or /Examples directory

Related

unicode values in phpexcel are not exporting

I am trying to export unicode values to excel using phpexcel.
The code works perfectly in my localhost but when uploaded to live it is giving junk values.
Framework used : Codeigniter
Server : CENTOS 6.9 , php7, easy Apache 4.
public function export_approvedApplication() {
error_reporting(E_ALL);
ini_set('display_errors', 1);
//load our new PHPExcel library
$this->load->library('excel');
//activate worksheet number 1
$this->excel->setActiveSheetIndex(0);
//name the worksheet
$this->excel->getActiveSheet()->setTitle('Taluk Excel');
//make the font become bold
$this->excel->getActiveSheet()->getStyle('A1')->getFont()->setBold(true);
$this->excel->getActiveSheet()->getStyle('B1')->getFont()->setBold(true);
$output = 'ಹೆಸರು';
//$output = mb_convert_encoding($output, 'UTF-16LE', 'UTF-8');
//$output = utf8_encode($output);
$content_array = array(array('SL No', $output));
// read data to active sheet
$this->excel->getActiveSheet()->fromArray($content_array);
$filename = 'ExportEXCEL.xls'; //save our workbook as this file name
header('Content-Encoding: UTF-8');
header('Content-Type: application/vnd.ms-excel; charset=UTF-8'); //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, 'Excel5');
//force user to download the Excel file without writing it to server's HD
$objWriter->save('php://output');
}
I have also tried with 'mb_convert_encoding' but was unsuccessfull as it was giving
Call to undefined function mb_convert_encoding()
Then I tried installing mbstring , however I was not able to do the same.
Local environment : ubuntu 16 , php7
It would be of great help if anyone could help me with this.
Thank you
Issue is fixed.
#Mark and #Gaurav : Thank you so guys for your suggestions and prompt replies.
As I have mentioned above in my post and in my replies I was not able to render unicode values in my excel export using PHPEXCEL .
After googling much and using 'mb_convert_encoding' I found that I have to enable mbstring extension . For doing that I tried using terminal (used 'yum install php56-mbstring' , 'used REPO', 'tried download') I dont know why but could not succeed in the same.
Then I could enable the mbstring only using WHM login
I followed the link below
LINK HERE
Thank you

Which files from phpexcel library are necessary to export data into excel2007 format ? I want minimum number of files

I am using PHPExcel_1.7.9 library for exporting data in form of .xlsx format. this library contains 223 files and 53 folders. I want files and folders which are useful for my functionality only (to avoid unnecessary file upload on server).
Bellow is code, working absolutely fine.
//----CODE TO EXPORT DATA DIRECTLY AS EXCEL(.XLSX) WITHOUT HELP OF CSV FORMAT ----------
require_once ROOT_PATH . '/Classes/PHPExcel.php';
$header=$exportPlugin->getCommonHeader($case,$frmDate,$toDate,$empid,$divId,$excpCode,$reportType,$varType);
$data=$exportPlugin->getCommonFilterData($case,$frmDate,$toDate,$empid,$divId,$excpCode,$reportType,$varType);
$base_path1 = dirname(__FILE__);
$lastSpacePosition1 = strrpos($base_path1,"\lib");
$base_path1 = substr($base_path1,0,$lastSpacePosition1);
$csvName=str_replace(':','',$csvName);
$pathh=$base_path1.'\fileexports\\'.$csvName.".xlsx";
//file_put_contents($pathh, $csvContents);
$objPHPExcel=new PHPExcel();
$objPHPExcel->setActiveSheetIndex(0);
$alpha=Array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z');
$objPHPExcel->getDefaultStyle()->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
for($i=0;$igetActiveSheet()->setCellValue($alpha[$i].'1' , $header[$i]);
}
$n=3;
for ($i = 0; $i getActiveSheet()->setCellValue($alpha[$j]. $n, $data[$i][$j]);
}
$n++;
}
foreach(range('A','Z') as $columnID) {
$objPHPExcel->getActiveSheet()->getColumnDimension($columnID)->setAutoSize(true);
}
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel,'Excel2007');
$objWriter->save($pathh);
ob_end_clean();
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment; filename='. $pathh);
header('Cache-Control: max-age=0');
readfile($pathh);
unlink($pathh);
//-----------------------------------------------------------------------------------------
Please tell me how many and which files or folders from PHPExcel library , should I keep in project and which may I delete ???
working environment-
.......Server - XAMPP
............Apache/2.2.11 (Win32) DAV/2 mod_ssl/2.2.11 OpenSSL/0.9.8i PHP/5.2.9
............MySQL client version: 5.0.51a
............PHP extension: mysql
.......O.S - WINDOWS7
If you absolutely have to do this:
Remove all locale files except those in the /en subdirectory. Remove all named Readers and Writers and associated subdirectories except those you need (you still need the Abstracts and the Interfaces though). Remove all CachedObjectStorage options except Memory/Icache/CacheBase. Remove Charts if you don't use them. Remove Shared PCLZip, OLE files and Escher.... and hope that I've not miscalculated

Blocks can only contain strings error when saving to disk

Background
I'm generating an Excel sheet that get's emailed to a certain address. It works perfectly on localhost (saves perfectly, can't test the mailing as I have no local mailserver running). When I host it, I run into some problems.
What problems
I've narrowed it down to this line:
$this->PhpExcel->saveToDisk($path);
$path is a custom path that is set at runtime. When I run that, it saves the file to disk but it gives me this:
This is a function in a custom helper class. Below is the code for the function:
public function saveToDisk($path) {
// set layout
$this->_View->layout = '';
// headers
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="'.$filename.'"');
header('Cache-Control: max-age=0');
// writer
$objWriter = PHPExcel_IOFactory::createWriter($this->xls, 'Excel2007');
ob_end_clean();
$objWriter->save($path);
// clear memory
$this->xls->disconnectWorksheets();
}
But here is the catch. When I output it to browser, by changing $objWriter->save($path); to $objWriter->save('php://output'); it gives me no error and exports the file perfectly.
Question
I've googled the error and tried my best to find the solution, but to no avail. The amount of info available on this error is staggeringly scarce or outdated. Could someone please tell me what it is that I'm missing or doing wrong?
When you've saved the file to disk, CakePHP still expects you to give it something to return to the browser that made the request, even if it's just a message to say that the file has been saved successfully, or that the email has been sent successfully.
If you're saving to disk, you don't want to send the headers because the server isn't going to be returning an Excel file, so no headers.
I fixed it by removing this line:
ob_end_clean();

PHPExcel Warning/Error when opening document

I have built an Excel document using the PHPExcel Library. My document opens and looks fine both in Numbers (mac) and Office 2007 (windows). I am saving my file as a .xlsx file.
When I open the file, although it displays properly, it gives the following errors/warnings.
In Numbers, it gives the warning "Password protection on sheets isn't supported and was removed"
In Office 2007 it gives te error "Excel found unreadable content in 'filename.xlsx'. Do you want to recover the contents of this workbook? If you trust the source of this workbook, click Yes." When I click yes, everything displays fine, and it says "Removed Records: Merge cells from /sl/worksheets/sheet1.xml part".
It should be noted that I did not add any password to my file. I also have only one workbook. Anyone know how I can get rid of these or what might be causing them?
I've had the same problem and i resolved simply putting an
exit();
justafter the $objWriter->save('php://output'); command.
Eg.
// Redirect output to a client’s web browser (Excel2007)
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="industrializzazione_RTW_'.$rows[0]['stagione'].'.xlsx"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');
exit();
I ran into something similar while using CakePHP building a spreadsheet with mergecells. It works fine for Excel 2003 but not Excel 2007 format. If I build the 2007 spreadsheet using:
$objPHPExcel->getActiveSheet()->mergeCells('C30:E30');
the spreadsheet loads fine. However using a variable in any way such as these variants:
$mergestr = '\'C'.(30+$i).':E'.(30+$i).'\'';
$objPHPExcel->getActiveSheet()->mergeCells($mergestr);
$objPHPExcel->getActiveSheet()->mergeCells(eval("return \$$mergestr;"));
$objPHPExcel->getActiveSheet()->mergeCells('\'C'.(30+$i).':E'.(30+$i).'\'');
$objPHPExcel->getActiveSheet()->mergeCells('C'.(30+$i).':E'.(30+$i));
I get the same error you do. I'm not sure if there is a way to escape a variable in a way PHPExcel will like for the Excel2007 writer. The Excel5 writer works fine with the last example above. Hope this helps someone.

Export mySQL to excel or csv

I'm no php expert (a mere beginner) but need some help!
After hours searching Google and trying out about 100 different scripts, I finally found one that does what I need - almost.
Basically, my site has a button marked 'Export to Excel'. Visitor to site clicks button and a download begins containing all data from a specified table.
I found this on here - PHP code to convert a MySQL query to CSV
which does exactly what I want except the user sees the following error when trying to open the file:
Error - 'The file you are trying to open, 'export.xls', is in a different format than specified by the file extension. Verify that the file is not corrupted and is from a trusted source before opening the file. Wo you want to open the file now?'
User clicks 'Yes' and file opens with all data! Brilliant! Except users will not open the file with this error.
I would be very grateful if someone knows a way to fix this.
Many thanks
TT
Or, you could just change the script in the above solution to return a file with the .csv extension. .csv files are associated with Excel, so they should open directly.
Ok, this results from a feature specified by Excel 2007 called Extension Hardening. You can turn it off, but that can only be done client-side. If you click "OK" or "Yes" the file should open anyway. Check this blog post for more info.
EDIT: What this means is that Excel is finding that the file is of a different type (say HTML or CSV) that what is specified by the file extension. Therefore Excel wants to warn you that this file is not what it says it is. Unless you are going to create native Excel files on the server then prompt the user to download them, there is no getting around this error except for each user to turn off Extension Hardening on their own computer.
if you make the first letters “ID” of a text file Excel incorrectly
assumes you are trying to open an SYLK file.
Meaning if the first row & column value is "ID", Excel will throw this warning. Just change it from "ID" to anything else.
Credit: http://alunr.com/excel-csv-import-returns-an-sylk-file-format-error/
Dim objXL As Excel.Application
Dim objWkb As Excel.Workbook
Set objXL = New Excel.Application
'turn off excel warnings
objXL.DisplayAlerts = False
'Open the Workbook
Set objWkb = objXL.Workbooks.Open(fpath)
functions sendFile($filename,$content_type="application/ms-excel") {
header('Content-type: '.$content_type);
header('Content-disposition: Attachment; filename=' . $filename);
readfile($filename);
}
I had the same problem so I looked at the following link: PHP code to convert a MySQL query to CSV
I modified one of the answers to get the headers to work.
include('DBFILE.PHP');
$select="SELECT * FROM SOMETable";
$result = mysqli_query($conn, $select);
if (!$result) die('Couldn\'t fetch records');
$num_fields = mysql_num_fields($result);
//This is what I changed...
$headers ="";
while ($property = mysqli_fetch_field($result)) {
$headers.= $property->name.",";
}
$headers.="\n";
//////
$fp = fopen('php://output', 'w');
if ($fp && $result) {
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="export.csv"');
header('Pragma: no-cache');
header('Expires: 0');
fputcsv($fp, $headers);
while ($row = $result->fetch_array(MYSQLI_NUM)) {
fputcsv($fp, array_values($row));
}
die;
}
I Tested this and it works like a charm, you just need to add your db connection or include the db.php file that you have.
you can change the name of the file if you edit the following line
header('Content-Disposition: attachment; filename="export.csv"');
Change export to what ever name you like.

Categories