PHPExcel German vowels - 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;
?>

Related

Export mysql table data as xlsx format using phpspreadsheet,can't not importing

I used phpspreadsheet to export mysql table data as XLSX format but after exporting when I import the XLSX file its not importing.the exported xlsx file data is ok.If I copy the data in another XLSX file then it works perfectly.
Thanks in advance!
<?php
require 'connect.php';
require 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\IOFactory;
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1', 'Program');
$sheet->setCellValue('B1', 'FormalCode');
$sheet->setCellValue('C1', 'Title');
$sql = "select * from class_routine";
$result = $conn->query($sql);
if($result->num_rows > 0){
$n = 1;
while($row = $result->fetch_assoc()){
$rowNum = $n + 1;
$sheet->setCellValue('A' .$rowNum, $row['Program']);
$sheet->setCellValue('B' .$rowNum, $row['FormalCode']);
$sheet->setCellValue('C' .$rowNum, $row['Title']);
$n++;
}
}
$filename = 'ClassRoutine-template-'.time().'.xlsx';
// 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.
$writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save('php://output');
Full Code Here https://pastebin.com/imP2QdLm
Giving this warnings when importing the exported xlsx file in import page:
Warning: XMLReader::open(): Empty string supplied as input in C:\xampp\htdocs\corap\vendor\SpreadsheetReader_XLSX.php on line 959
Warning: XMLReader::read(): Load Data before trying to read in C:\xampp\htdocs\corap\vendor\SpreadsheetReader_XLSX.php on line 995
Warning: XMLReader::read(): Load Data before trying to read in C:\xampp\htdocs\corap\vendor\SpreadsheetReader_XLSX.php on line 995

PHPExcel export not working : displays "the website cannot be reached"

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.

Blank Page and No Download PHPExcel

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

Browser display PHPExcel sheet instead of open "Save dialog" when export

I´m trying to export some data from mysql to "PHPExcel".
I would like to have a "Save dialog" rather than saving the file on server. I have google it but cannot find anything more than "Add another header".. so i have been adding alot of headers :)
But both Chrome and Firefox will only display the sheet.
No, Save dialog opens.
Why?
To save the file on server works just fine!
PHP
<?php
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header("Content-Disposition: attachment; filename=\"results.xlsx\"");
header("Cache-Control: max-age=0");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Description: File Transfer");
header("Content-Transfer-Encoding: Binary");
//Load db connection
require("conf.php");
//Check if usr is logged in
if(empty($_SESSION['user'])){
header("Location: index.php");
die("Redirecting to index.php");
}
//Check IF post
if(!empty($_POST['objNr'])){
//Store post in var
$objNr = $_POST['objNr'];
/** Error reporting */
error_reporting(E_ALL);
//Load phpexcel includes
require '../Classes/PHPExcel.php';
/** PHPExcel_Writer_Excel2007 */
include '../Classes/PHPExcel/Writer/Excel2007.php';
// Create new PHPExcel object
$objPHPExcel = new PHPExcel();
// Set properties
$objPHPExcel->getProperties()->setCreator("Maarten Balliauw");
$objPHPExcel->getProperties()->setLastModifiedBy("Maarten Balliauw");
$objPHPExcel->getProperties()->setTitle("Office 2007 XLSX Test Document");
$objPHPExcel->getProperties()->setSubject("Office 2007 XLSX Test Document");
$objPHPExcel->getProperties()->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.");
// Add some data
$objPHPExcel->setActiveSheetIndex(0);
$objPHPExcel->getActiveSheet()->SetCellValue('A1', 'Nr');
$objPHPExcel->getActiveSheet()->SetCellValue('B1', 'Höjd');
$objPHPExcel->getActiveSheet()->SetCellValue('C1', 'Typ');
$objPHPExcel->getActiveSheet()->SetCellValue('D1', 'Längd');
$objPHPExcel->getActiveSheet()->SetCellValue('E1', 'AV');
$objPHPExcel->getActiveSheet()->SetCellValue('F1', 'Öppningar');
$objPHPExcel->getActiveSheet()->SetCellValue('G1', 'Vikt');
//Fetch data from DB
$query = "SELECT * FROM element WHERE objekt_nr = '$objNr' ORDER BY length(element_nr), element_nr ASC";
try{
$stmt = $db->prepare($query);
$result = $stmt->execute();
}
catch(PDOException $ex){
die("Failed to run query: " . $ex->getMessage());
}
//Insert på first row after heading
$row = 2;
while($value = $stmt->fetch()){
//Set start Column
$column = "A";
$objPHPExcel->getActiveSheet()->SetCellValue($column++.$row, $value['element_nr']);
$objPHPExcel->getActiveSheet()->SetCellValue($column++.$row, $value['hojd']);
$objPHPExcel->getActiveSheet()->SetCellValue($column++.$row, $value['typ']);
$objPHPExcel->getActiveSheet()->SetCellValue($column++.$row, $value['langd']);
$objPHPExcel->getActiveSheet()->SetCellValue($column++.$row, $value['avdrag']."");
$objPHPExcel->getActiveSheet()->SetCellValue($column++.$row, $value['oppningar']."");
$objPHPExcel->getActiveSheet()->SetCellValue($column++.$row, $value['vikt']);
//INCREASE Row Nr
$row++;
}
// Rename sheet
$objPHPExcel->getActiveSheet()->setTitle($objNr);
// Write file to the browser
$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
$objWriter->save('file.xlsx');
}
else{
echo 'Välj objektnummer..';
}
You need this $objWriter->save('php://output'); instead of $objWriter->save('file.xlsx');

Retrieve table in database to phpexcel

I am using php excel export the data in database to Excel format.
I can retrieve all the data from database to Excel ady. But if i wanna to retrieve the column name of the table, how i going to do. Anyone can help?
Here's my code:
<?php
header("Content-Type:application/vnd.ms-excel");
header("Content-Disposition:attachment;filename=product.xls");
header("Pragma:no-cache");
header("Expires:0");
header('Content-Type: text/html; charset=UTF-8');
header("Content-type: application/octetstream");
header('Content-Disposition: attachment; filename="export.csv"');
/** Error reporting */
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 '../Classes/PHPExcel.php';
require_once '../Classes/PHPExcel/Writer/Excel2007.php';
require_once '../Classes/PHPExcel/IOFactory.php';
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("litako", $con);
$objPHPExcel = new PHPExcel();
$res= mysql_query("SELECT * FROM vendorlist ");
/** Error reporting */
error_reporting(E_ALL);
date_default_timezone_set('Europe/London');
$objPHPExcel = new PHPExcel();
if(!$res){
die("Error");
}
$col = 0;
$row = 3;
while($mrow = mysql_fetch_assoc($res)) {
$col = 0;
foreach($mrow as $key=>$value) {
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $value);
$col++;
}
$row++;
}
// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$objPHPExcel->setActiveSheetIndex(0);
// Save Excel 2007 file
$objPHPExcel->setActiveSheetIndex(0);
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="report.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;
You already have the column name in your while loop where you call mysql_fetch_assoc. The $key value is the column name. So here is an updated portion of your code:
while($mrow = mysql_fetch_assoc($res)) {
$col = 0;
foreach($mrow as $key=>$value) {
// TODO: Do Something With the Column Name like set the row header. Note this crude code sets it every time. You really just want to do it the first time only.
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, 0, $key);
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row + 1, $value);
$col++;
}
$row++;
}

Categories