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
Related
This code generates an excel file from MySQL in PHP and downloads it.
But the issue is that the excel file opens in google chrome's
"Office Editing for Docs, Sheets & Slides"
extension,
but says invalid excel file when I try to open it in Microsoft excel.
How to solve this?
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment; filename='.$fileName);
echo implode("\t", array_values($heading)) . "\n";
while( $row = mysqli_fetch_array($result)) {
$record=array();
$record[]=$row["join_date"];
$record[]=$agents[$row["agent_id"]];
$record[]=$row["name"];
$record[]=$row["amount"];
$record[]=$brokerages[$row["brokerage"]];
echo implode("\t", array_values($record)) . "\n";
}
Your posted data is not Excel or CSV. You are sending TSV
Correct content type for your file is "text/tab-separated-values"
See https://github.com/PHPOffice/PhpSpreadsheet/blob/master/samples/Basic/01_Simple_download_xls.php how to make your data downloaded as XLS document.
It's not really an Excel file. It's a TSV file. With the right file extension (.tsv, not .xlsx), Excel can open it too.
I try to convert csv to xlsx using PHPExcel tools, when i run the script i got error and i got chinese font in excel file after convert:
Error PHP EXECL
here is my code :
<?php
include 'PHPExcel/PHPExcel/IOFactory.php';
$objReader = PHPExcel_IOFactory::createReader('CSV');
// If the files uses a delimiter other than a comma (e.g. a tab), then tell the reader
$objReader->setDelimiter("\t");
// If the files uses an encoding other than UTF-8 or ASCII, then tell the reader
$objReader->setInputEncoding('UTF-16LE');
$objPHPExcel = $objReader->load('myfilebeforeconvert.csv');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('afterconvert.xls');
what my fault ? please tell me
You have provided little information but you can check this example for help.
This might also help, check this link
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
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
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.