Can anyone help me with PHPExcel?
I have this code...
<?php
session_start();
include 'dbconnect.php';
date_default_timezone_set("Europe/Rome");
if (!isset($_SESSION['user'])) {
header("Location: index.php");
}
$query = mysql_query("SELECT * FROM partner1 WHERE uid=" . $_GET['id']);
while ($userRow1 = mysql_fetch_assoc($query)) {
/** Error reporting */
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
date_default_timezone_set('Europe/Rome');
if (PHP_SAPI == 'cli')
die('This example should only be run from a Web Browser');
/** Include PHPExcel */
require_once dirname(__FILE__) . '/Classes/PHPExcel.php';
// Create new PHPExcel object
$objPHPExcel = new PHPExcel();
$objPHPExcel->getActiveSheet()->getStyle("A1:A27")->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle("A1:A27")->getFont()->setSize(16);
$objPHPExcel->getActiveSheet()->getRowDimension('1')->setRowHeight(40);
$objPHPExcel->getActiveSheet()->getRowDimension('2')->setRowHeight(40);
$objPHPExcel->getActiveSheet()->getRowDimension('3')->setRowHeight(40);
$objPHPExcel->getActiveSheet()->getRowDimension('4')->setRowHeight(40);
$objPHPExcel->getActiveSheet()->getRowDimension('5')->setRowHeight(40);
$objPHPExcel->getActiveSheet()->getRowDimension('6')->setRowHeight(40);
$objPHPExcel->getActiveSheet()->getRowDimension('7')->setRowHeight(40);
$objPHPExcel->getActiveSheet()->getRowDimension('8')->setRowHeight(40);
$objPHPExcel->getActiveSheet()->getRowDimension('9')->setRowHeight(40);
$objPHPExcel->getActiveSheet()->getRowDimension('10')->setRowHeight(40);
$objPHPExcel->getActiveSheet()->getRowDimension('11')->setRowHeight(40);
$objPHPExcel->getActiveSheet()->getRowDimension('12')->setRowHeight(40);
$objPHPExcel->getActiveSheet()->getRowDimension('13')->setRowHeight(40);
$objPHPExcel->getActiveSheet()->getRowDimension('14')->setRowHeight(40);
$objPHPExcel->getActiveSheet()->getRowDimension('15')->setRowHeight(40);
$objPHPExcel->getActiveSheet()->getRowDimension('16')->setRowHeight(40);
$objPHPExcel->getActiveSheet()->getRowDimension('17')->setRowHeight(40);
$objPHPExcel->getActiveSheet()->getRowDimension('18')->setRowHeight(40);
$objPHPExcel->getActiveSheet()->getRowDimension('19')->setRowHeight(40);
$objPHPExcel->getActiveSheet()->getRowDimension('20')->setRowHeight(40);
$objPHPExcel->getActiveSheet()->getRowDimension('21')->setRowHeight(40);
$objPHPExcel->getActiveSheet()->getRowDimension('22')->setRowHeight(40);
$objPHPExcel->getActiveSheet()->getRowDimension('23')->setRowHeight(40);
$objPHPExcel->getActiveSheet()->getRowDimension('24')->setRowHeight(40);
$objPHPExcel->getActiveSheet()->getRowDimension('25')->setRowHeight(40);
$objPHPExcel->getActiveSheet()->getRowDimension('26')->setRowHeight(40);
$objPHPExcel->getActiveSheet()->getRowDimension('27')->setRowHeight(40);
$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setAutoSize(true);
$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setAutoSize(true);
// Set document properties
$objPHPExcel->getProperties()->setCreator("Test 123")
->setLastModifiedBy("-")
->setTitle("" . $userRow1['nome'] . " " . $userRow1['cognome'] . "")
->setSubject("-")
->setDescription("-")
->setKeywords("-")
->setCategory("-");
// Add some data
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A1', 'Codice Op')
->setCellValue('A2', 'DATA:')
->setCellValue('A3', 'DATI CLIENTE')
->setCellValue('A4', 'Nome')
->setCellValue('A5', 'Cognome')
->setCellValue('A6', 'Data e Luogo di nascita')
->setCellValue('A7', 'Via')
->setCellValue('A8', 'Cumune,Cap,PR')
->setCellValue('A9', 'Telefono rete fissa')
->setCellValue('A10', 'Recapito Alternativo')
->setCellValue('A11', 'Tipo Documento')
->setCellValue('A12', 'Ente di rilascio')
->setCellValue('A13', 'Data Rilascio')
->setCellValue('A14', 'Data Scadenza')
->setCellValue('A15', 'Codice Fiscale')
->setCellValue('A16', 'PROPOSTA')
->setCellValue('A17', 'OFFERTA')
->setCellValue('A18', 'TIM VISION')
->setCellValue('A19', 'Modem (s/n)')
->setCellValue('A20', 'Gestore telefonico')
->setCellValue('A21', 'Codice di migrazione1')
->setCellValue('A22', 'Codice di migrazione2')
->setCellValue('A23', 'ICCID')
->setCellValue('A24', 'Numero per Smart')
->setCellValue('A25', 'Gestore Mobile')
->setCellValue('A26', 'Inserimento Elenco Telefonico')
->setCellValue('A27', 'NATIVO TELECOM')
->setCellValue('B1', '-')
->setCellValue('B2', '' . $userRow1['data'] . '')
->setCellValue('B3', '-')
->setCellValue('B4', '' . $userRow1['nome'] . '')
->setCellValue('B5', '' . $userRow1['cognome'] . '')
->setCellValue('B6', '' . $userRow1['natoil'] . '')
->setCellValue('B7', '' . $userRow1['via'] . '')
->setCellValue('B8', '' . $userRow1['cumune'] . ' , ' . $userRow1['cap'] . ' , ' . $userRow1['provincia'] . '')
->setCellValue('B9', '' . $userRow1['numero'] . '')
->setCellValue('B10', '' . $userRow1['ricapitodicell'] . '')
->setCellValue('B11', '' . $userRow1['documento'] . '')
->setCellValue('B12', '' . $userRow1['rilascio'] . '')
->setCellValue('B13', '' . $userRow1['scadenza'] . '')
->setCellValue('B14', '' . $userRow1['codicefiscale'] . '')
->setCellValue('B15', '-')
->setCellValue('B16', '' . $userRow1['ofertascelta'] . '')
->setCellValue('B17', '-')
->setCellValue('B18', '-')
->setCellValue('B19', '' . $userRow1['operatoretelefonico'] . '')
->setCellValue('B20', '' . $userRow1['codicemigrazione'] . '')
->setCellValue('B21', '' . $userRow1['iccid'] . '')
->setCellValue('B22', '' . $userRow1['celloftsm'] . '')
->setCellValue('B23', ' ')
->setCellValue('B24', '-')
->setCellValue('B25', '-')
->setCellValue('B26', '-')
->setCellValue('B27', '-');
// Rename worksheet
$objPHPExcel->getActiveSheet()->setTitle('Simple');
$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(20);
$objPHPExcel->getActiveSheet()->getDefaultRowDimension()->setRowHeight(15);
// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$objPHPExcel->setActiveSheetIndex(0);
// Rename worksheet
$objPHPExcel->getActiveSheet()->setTitle('Simple');
$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(20);
$objPHPExcel->getActiveSheet()->getDefaultRowDimension()->setRowHeight(15);
// 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;
When I try to read and download my database data to excel format I get a blank page and no download.
I don't get any error on this. I don't know what to do lol
Obvious problems (just wading through this wall of code)
if(!isset($_SESSION['user']))
{
header("Location: index.php");
}
will still continue executing the rest of the code
You're including PHPExcel, creating a new PHPExcel object, and sending the response to the browser for every single row that you iterate in the while $userRow1 = mysql_fetch_assoc($query)) loop.... I'm assuming that you really want each row to be written to the same file
EDIT
Trying to keep the answer simple, rather than a wall of code, your structure should be something like:
include 'dbconnect.php';
/** Include PHPExcel */
require_once dirname(__FILE__) . '/Classes/PHPExcel.php';
// Create new PHPExcel object
$objPHPExcel = new PHPExcel();
$query=mysql_query("SELECT * FROM partner1 WHERE uid=".$_GET['id']);
while($userRow1 = mysql_fetch_assoc($query)) {
// Add some data
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A1', 'Codice Op')
.....
;
}
// 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;
Also note that the mysql extension is deprecated in PHP, you should really be using mysqli or PDO with prepared statements/bind variables to protect your script against SQL injection
Related
I am currently having a problem with my PHP code as it corrupts the data/xlsx file when exporting it from HTML.
i am viewing PHP Mailer scripts which has multiple pages connected to it.
This is my PHP XLS Function.
this->_request->download ? true : false;
$htmlPath = realpath(dirname(__FILE__) . "/../../public/reports/html/") . "/" . $fileName;
$fileSource = file_get_contents($htmlPath);
preg_match('!<title>([^<]+)!', $fileSource, $title);
$title = trim($title[1]);
if (stristr($fileSource, '<graph>')) {
$fileSource = preg_replace('!<graph>[^<]+</graph>!is', '', $fileSource);
file_put_contents($htmlPath, $fileSource);
}
file_put_contents($htmlPath,preg_replace('!<title>[^<]+</title>!is','',$fileSource));
$reader = new PHPExcel_Reader_HTML;
$content = $reader->load($htmlPath);
// Pass to writer and output as needed
$objWriter = PHPExcel_IOFactory::createWriter($content, 'Excel2007');
$download = 1;
// Redirect output to a client’s web browser (Excel5)
//header('Content-Type: application/vnd.ms-excel');
$fileName = str_replace(' ', '-', ($title . "-" . date('Y-m-d')));
if ($download) {
// Redirect output to a client’s web browser (Excel2007)
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
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
header('Content-Disposition: attachment;
filename=' . $fileName . ".xlsx")
this is my caller function
if ($reportRow->reportString) {
$reportRow->reportString = stripslashes($reportRow->reportString);
if (!stristr($reportRow->reportString, '</body>'))
$reportRow->reportString = $reportRow->reportString . "</table></body></html>";
$fileName = time() . rand(111, 222);
$htmlPath = realpath(dirname(__FILE__) . "/../../public/reports/html/") . "/" . $fileName;
if ($headerPath) {
$reportRow->html_string = preg_replace('!(\s*</htmlpageheader>)!', '$1<img width="100%" style="clear:both" id="headerPath" src="' . $headerPath . '" />', $reportRow->html_string);
}
$corp_name = preg_replace('!\s+!',' ',$userSessionData->corp_name);
$reportRow->reportString = preg_replace_callback(
'!<title>([^<]+)!is',
function($matches) use ($corp_name){
return '<title>' . $corp_name . '_' . preg_replace('!\s+!',' ',$matches[1]);
},
$reportRow->reportString
);
file_put_contents($htmlPath, $reportRow->reportString);
$kilobites = filesize($htmlPath);
$kilobites = $kilobites / 1024;
$kilobites = 0;
if ($ifXLS) {
echo json_encode(array(
'reportPath' => '/helper/file-To-xls/fileName/' . $fileName,
'error' => false
));
would anyone have any ideas on how to fix this issue?
you can use CSV functions or PHPExcel to do it straight forward
or you can try like below
<?php
$file="1.xls";
$html="<table><tr><td>Col1</td><td>Col2</td></tr></table>";
header("Content-type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=$file");
echo $html;
?>
The header for .xlsx files is Content-type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet if you prefer to export it as .xlsx
I have cloned a project from server and installed in my local setup.
I am trying to export excel file to the browser using PHPExcel. It is working fine in the server. But there is problem with the local setup.
Also I checked number of columns and fields and they are fine.
Below is the code:
<?php
//PHPExcel starts from here
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
date_default_timezone_set('Asia/Kathmandu');
if (PHP_SAPI == 'cli')
die('Error in loading PHPExcel');
// Create new PHPExcel object
$objPHPExcel = new PHPExcel();
// Set document properties
$objPHPExcel->getProperties()->setCreator("GBD Admin")
->setLastModifiedBy("GBD Admin")
->setTitle("Weekly checkin/checkout log")
->setDescription("Test document for PHPExcel, generated using PHP classes.")
->setKeywords("Checkin/Checkout Logs")
->setCategory("Checkin/Checkout Logs");
// Add some data
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A1', 'Date of Export')
->setCellValue('B1', $now)
->setCellValue('A3', 'Employee Name')
->setCellValue('B3', ' Checkin-date')
->setCellValue('C3', ' Checkin-time')
->setCellValue('D3', ' Checkout-date')
->setCellValue('E3', ' Checkout-time')
// ->setCellValue('F3', ' Total-time Spent')
// ->setCellValue('G3', ' Over-time')
->setCellValue('F3', ' Early checkout-remarks')
->setCellValue('G3', ' Late checkin-remarks');
// Newly added statement below
// ->setCellValue('H3', ' Absent/Leave Remarks');
$objPHPExcel->getActiveSheet()->getStyle('A1:B1')->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('A3:H3')->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->fromArray($results, null, 'A5');
$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(45);
$objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(45);
// Rename worksheet
$objPHPExcel->getActiveSheet()->setTitle('Login-data-' . $now);
// 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="Login_data_' . $now . '.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;
?>
I have been getting this error:
This site can’t be reached
The webpage at http://localhost/gbdportal-new/Export might be
temporarily down or it may have moved permanently to a new web
address. ERR_INVALID_RESPONSE
It is working fine with the live version currently running on the server. What could be the problem?
This is a bug in phpExcel in combination with php7:
https://github.com/PHPOffice/PHPExcel/issues/716
on Line 581 of file PHPExcel/Classes/PHPExcel/Calculation/Functions.php there is a " break" , simply comment.
I have many arrays and i print it into excel using PHPExcel. Some times it need many column to write. It is over 5000 column.
The problem is sometime even the column is over from 5000 column, it can be print succeesfully but sometime it show as corrupted file.
I have read this : Why PHPExcel does not allow to write more than 5000 rows
But still im confusing.
This is my code :
<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
date_default_timezone_set('Europe/London');
if (PHP_SAPI == 'cli')
die('This example should only be run from a Web Browser');
/** Include PHPExcel */
require_once 'PHPExcel.php';
// Create new PHPExcel object
$objPHPExcel = new PHPExcel();
// Set document properties
$objPHPExcel->getProperties()->setCreator("Valerian Timothy")
->setLastModifiedBy("Valerian Timothy")
->setTitle("Excel Document")
->setSubject("Data Mining")
->setDescription("Count how many words exists.")
->setKeywords("Data Mining")
->setCategory("Data Mining");
// Add some data
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A1', 'Username')
->setCellValue('B1', 'Jumlah')
->setCellValue('C1', 'Hashtag')
->setCellValue('D1', 'Jumlah')
->setCellValue('E1', 'Etc')
->setCellValue('F1', 'Jumlah')
->setCellValue('G1', 'Date')
->setCellValue('H1', 'Jumlah');
// Miscellaneous glyphs, UTF-8
if($_SESSION['username'] != "")
{
$w = 2;
foreach($_SESSION['username'] as $user => $jumlah)
{
$cellUser = 'A' . $w;
$cellJumlah = 'B' . $w;
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue($cellUser, $user)
->setCellValue($cellJumlah, $jumlah);
$w++;
}
}
if($_SESSION['hashtag'] != "")
{
$x = 2;
foreach($_SESSION['hashtag'] as $hashtag => $jumlah)
{
$cellUser = 'C' . $x;
$cellJumlah = 'D' . $x;
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue($cellUser, $hashtag)
->setCellValue($cellJumlah, $jumlah);
$x++;
}
}
if($_SESSION['etc'] != "")
{
$y = 2;
foreach($_SESSION['etc'] as $etc => $jumlah)
{
$cellUser = 'E' . $y;
$cellJumlah = 'F' . $y;
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue($cellUser, $etc)
->setCellValue($cellJumlah, $jumlah);
$y++;
}
}
if(!empty($_SESSION['tanggal']))
{
$z = 2;
foreach($_SESSION['tanggal'] as $date => $jumlah)
{
$cellUser = 'G' . $z;
$cellJumlah = 'H' . $z;
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue($cellUser, $date)
->setCellValue($cellJumlah, $jumlah);
$z++;
}
}
foreach(range('A','H') as $columnID) {
$objPHPExcel->getActiveSheet()->getColumnDimension($columnID)
->setAutoSize(true);
}
// Rename worksheet
$objPHPExcel->getActiveSheet()->setTitle('Simple');
// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$objPHPExcel->setActiveSheetIndex(0);
$today = strtotime(date('Y-m-d H:i:s'));
// Redirect output to a client’s web browser (Excel2007)
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="Data-Mining'.$today.'.xlsx"');
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, 'Excel2007');
$objWriter->save('php://output');
exit;
session_destroy();
?>
Could you help me to fix it ?
DevelopersI am using Yii1 and I want to generate a report using PHPExcel extension but my file is not ready to download, instead it appears in console. I also set headers but still file is not ready for download. I can't find exact answer. please resolve my problem
public function GenerateReport($dataProvider)
{
$phpExcelPath = Yii::getPathOfAlias('ext.phpexcel.Classes');
include($phpExcelPath . DIRECTORY_SEPARATOR . 'PHPExcel.php');
$objPHPExcel = new PHPExcel();
$fileName = 'report-'.uniqid().'.xlsx';
$objPHPExcel->getProperties()->setCreator("Palash Gupta");
$objPHPExcel->getProperties()->setTitle($fileName);
$objPHPExcel->getProperties()->setSubject("Placement Student List");
$objPHPExcel->getProperties()->setDescription("Placement Student List");
$objPHPExcel->setActiveSheetIndex(0);
$rowCount = 1;
$objPHPExcel->getActiveSheet()->SetCellValue('A' . $rowCount, 'Name');
$objPHPExcel->getActiveSheet()->SetCellValue('B' . $rowCount, 'Course');
$rowCount = 2;
foreach ($dataProvider->getData() as $data)
{
$objPHPExcel->getActiveSheet()->SetCellValue('A' . $rowCount, $data['sd_fname']);
$objPHPExcel->getActiveSheet()->SetCellValue('B' . $rowCount, $data['fk_mc_id']);
$rowCount++;
}
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="'.$fileName.'"');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');
}
Try this:
// Redirect output to a client’s web browser (Excel2007)
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
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');
exit;
Ref: https://github.com/PHPOffice/PHPExcel/blob/1.8/Examples/01simple-download-xls.php
I want to export a .xls-file from a database using phpexcel.
It works fine, however german vowels do make a lot of trouble.
Here is my code:
<?php
date_default_timezone_set('Europe/Rome');
/***** EDIT BELOW LINES *****/
$DB_Server = "localhost"; // MySQL Server
$DB_Username = "user"; // MySQL Username
$DB_Password = "passw"; // MySQL Password
$DB_DBName = "test2015"; // MySQL Database Name
$xls_filename = 'export_'.date('Y-m-d').'.xls'; // Define Excel (.xls) file name
/***** DO NOT EDIT BELOW LINES *****/
// Create MySQL connection
$sql = "select * from Teilnehmer join mannschaften mann ON mann.M_id = Teilnehmer.Team";
$Connect = #mysql_connect($DB_Server, $DB_Username, $DB_Password) or die("Failed to connect to MySQL:<br />" . mysql_error() . "<br />" . mysql_errno());
// Select database
$Db = #mysql_select_db($DB_DBName, $Connect) or die("Failed to select database:<br />" . mysql_error(). "<br />" . mysql_errno());
// Execute query
$result = #mysql_query($sql,$Connect) or die("Failed to execute query:<br />" . mysql_error(). "<br />" . mysql_errno());
/** Error reporting */
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
if (PHP_SAPI == 'cli')
die('This example should only be run from a Web Browser');
/** Include PHPExcel */
require_once dirname(__FILE__) . '/Classes/PHPExcel.php';
// Create new PHPExcel object
$objPHPExcel = new PHPExcel();
// Set document properties
$objPHPExcel->getProperties()->setCreator("Piok")
->setLastModifiedBy("PIOK")
->setTitle("Piok")
->setSubject("Piok")
->setDescription("Piok")
->setKeywords("Piok")
->setCategory("Piok");
// Add some data
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A1', 'Vorname')
->setCellValue('B1', 'Nachname')
->setCellValue('C1', 'Jahrgang')
->setCellValue('D1', 'Geschlecht')
->setCellValue('E1', 'Email')
->setCellValue('F1', 'FISICODE')
->setCellValue('G1', 'Mannschaft');
$startzeile = 2;
while($row = mysql_fetch_row($result))
{
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A'.$startzeile , $row[1])
->setCellValue('B'.$startzeile , $row[2])
->setCellValue('C'.$startzeile , $row[3])
->setCellValue('D'.$startzeile , $row[4])
->setCellValue('E'.$startzeile , $row[6])
->setCellValue('F'.$startzeile , $row[7])
->setCellValue('G'.$startzeile , $row[9]);
$startzeile++;
}
// Rename worksheet
$objPHPExcel->getActiveSheet()->setTitle($xls_filename);
// 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; charset=utf-8');
header('Content-Disposition: attachment;filename="'.$xls_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
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
exit;
?>
I use PHP 5.5
PHP-File encoding is set to UTF-8.
Thanks for your help.
Problems like this are usually a result of using a wrong encoding in one of the ways to get the Data from one medium to the other.
Your Excel Output sets the Charset to utf-8, which is the normal thing to do. Now you should check what encoding you use in your database and make sure it is UTF-8 as well.
And as a last step make sure you "talk" in UTF-8 to the database as well.
mysql_set_charset("UTF8", $Connect);
Try after clear output buffer.
Following answer will helpful for you. It's work for me.
<?php
date_default_timezone_set('Europe/Rome');
/***** EDIT BELOW LINES *****/
$DB_Server = "localhost"; // MySQL Server
$DB_Username = "user"; // MySQL Username
$DB_Password = "passw"; // MySQL Password
$DB_DBName = "test2015"; // MySQL Database Name
$xls_filename = 'export_'.date('Y-m-d').'.xls'; // Define Excel (.xls) file name
/***** DO NOT EDIT BELOW LINES *****/
// Create MySQL connection
$sql = "select * from Teilnehmer join mannschaften mann ON mann.M_id = Teilnehmer.Team";
$Connect = #mysql_connect($DB_Server, $DB_Username, $DB_Password) or die("Failed to connect to MySQL:<br />" . mysql_error() . "<br />" . mysql_errno());
// Select database
$Db = #mysql_select_db($DB_DBName, $Connect) or die("Failed to select database:<br />" . mysql_error(). "<br />" . mysql_errno());
// Execute query
$result = #mysql_query($sql,$Connect) or die("Failed to execute query:<br />" . mysql_error(). "<br />" . mysql_errno());
/** Error reporting */
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
if (PHP_SAPI == 'cli')
die('This example should only be run from a Web Browser');
/** Include PHPExcel */
require_once dirname(__FILE__) . '/Classes/PHPExcel.php';
//clean output buffer previously
ob_end_clean();
//start output buffer
ob_start();
// Create new PHPExcel object
$objPHPExcel = new PHPExcel();
// Set document properties
$objPHPExcel->getProperties()->setCreator("Piok")
->setLastModifiedBy("PIOK")
->setTitle("Piok")
->setSubject("Piok")
->setDescription("Piok")
->setKeywords("Piok")
->setCategory("Piok");
// Add some data
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A1', 'Vorname')
->setCellValue('B1', 'Nachname')
->setCellValue('C1', 'Jahrgang')
->setCellValue('D1', 'Geschlecht')
->setCellValue('E1', 'Email')
->setCellValue('F1', 'FISICODE')
->setCellValue('G1', 'Mannschaft');
$startzeile = 2;
while($row = mysql_fetch_row($result))
{
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A'.$startzeile , $row[1])
->setCellValue('B'.$startzeile , $row[2])
->setCellValue('C'.$startzeile , $row[3])
->setCellValue('D'.$startzeile , $row[4])
->setCellValue('E'.$startzeile , $row[6])
->setCellValue('F'.$startzeile , $row[7])
->setCellValue('G'.$startzeile , $row[9]);
$startzeile++;
}
// Rename worksheet
$objPHPExcel->getActiveSheet()->setTitle($xls_filename);
// 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; charset=utf-8');
header('Content-Disposition: attachment;filename="'.$xls_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
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
//Cleaning the ouput buffer
ob_flush();
exit;
?>