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

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');

Related

PHPSpreadhseet: Not getting output while export data from my database even not a single error?

I changed my code from PHPexcel to PHPSpreadsheet, every data is dynamic and coming from Mysql but my few data is not exporting even i am not getting any error and Data is showing while i print_r($name1) the variable,
Any help or suggestions is appreciated -
Here is my Converted code -
$inn_table = "";
for($i=0;$i<count($labels);$i++) {
if($result['qualification']['dd1']!="") {
for($j=0;$j<count($dd1);$j++) {
$temp = explode(">",$dd1[$j]);
if($temp[0]==$labels[$i]) {
$name = explode(">",$dd1[$j]);
echo '<pre>';
print_r($name[1]);
$inn_table .= '<td>'.$name[1].'</td>';
}
}
}
echo $inn_table;
Print_r output -
Yes
Category A
Others
TAS
6
How can I export it in excel with help of PHPSpreadheet
simple example -
Check labels
It checks with labels as you can see in my code and put data in the same label column cell as you can see in picture like if it matched with media type the it's print in media type row as you can see in picture
That's a example you can edit (in this example i use composer for install PHPSpreadheet):
require 'DB.php';
require 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx as xlsx; // Instead PHPExcel_Writer_Excel2007
use PhpOffice\PhpSpreadsheet\Worksheet\Drawing as drawing; // Instead PHPExcel_Worksheet_Drawing
use PhpOffice\PhpSpreadsheet\IOFactory as io_factory; // Instead PHPExcel_IOFactory
$query = 'SELECT * FROM ? WHERE ?';
$result = $mysqli->query($query);
$objPHPExcel = new Spreadsheet();
$objPHPExcel->setActiveSheetIndex(0);
//NAME WORKSHEET
$objPHPExcel->getActiveSheet()->setTitle("Test");
$objPHPExcel->getActiveSheet()
->getPageSetup()
->setOrientation(PhpOffice\PhpSpreadsheet\Worksheet\PageSetup::ORIENTATION_LANDSCAPE);
$objPHPExcel->getActiveSheet()
->getPageSetup()
->setPaperSize(PhpOffice\PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_A4);
$objPHPExcel->getActiveSheet()->SetCellValue('A12', 'ROW1');
$objPHPExcel->getActiveSheet()->SetCellValue('B12', 'ROW2');
$rowCount = 1;
}
while($row = $result->fetch_assoc()){
//BORDER
$objPHPExcel->getActiveSheet()->getStyle('A'.$rowCount)->applyFromArray($styleArray);
$objPHPExcel->getActiveSheet()->getStyle('B'.$rowCount)->applyFromArray($styleArray);
//VALUE
$objPHPExcel->getActiveSheet()->SetCellValue('A'.$rowCount, $row['row1']);
$objPHPExcel->getActiveSheet()->SetCellValue('B'.$rowCount, $row['row2']);
$rowCount++; //ADD COUNT
}
$objWriter = io_factory::createWriter($objPHPExcel, 'Xlsx');
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");;
header("Content-Disposition: attachment;filename=EXAMPLE.xlsx");
header("Content-Transfer-Encoding: binary ");
ob_end_clean();
ob_start();
$objWriter->save('php://output');
exit;
Db information and relative query is only example, remember to prepare stmt

PHPExcel: Some Lines are not exporting in my .xls file while importing but shown when i echo the output?

I am using PHPExcel with mysql and MongoDB to export data in Excel .XLS file but only in 1 Column some Lines are not showing and some are showing in same Columns while exporting although all are shown when i use $print_() to check output in browser
Here is my PHP Code -
$objPHPExcel = new PHPExcel();
$sheet = $objPHPExcel->getActiveSheet();
$sheet->setCellValue('M1', 'Headline');
$objPHPExcel->getActiveSheet()->getStyle('M')->applyFromArray($styleArray);
$objPHPExcel->getActiveSheet()->getStyle('M')->getFont()->setUnderline(true);
if ($result['type'] == "WEB") {
$sheet->setCellValue('M' . ($results + 2), $result['headline']);
$sheet->getCell('M' . ($results + 2))->getHyperlink()->setUrl($result['url']);
$sheet->getCell('M' . ($results + 2))->getHyperlink()->setTooltip('Navigate to website');
}
and this is my output
output
I post here an example without link (you can edit my code):
$objPHPExcel = new PHPExcel();
$result = $db->query("SELECT * FROM YOURTABLE") or die(mysql_error());
$objPHPExcel->setActiveSheetIndex(0);
$objPHPExcel->getActiveSheet()->SetCellValue('M1', 'Headline');
$objPHPExcel->getActiveSheet()->getStyle("M1")->getFont()->setBold(true);
$rowCount = 2;
while($row = $result->fetch_assoc()){
$objPHPExcel->getActiveSheet()->SetCellValue('M'.$rowCount, mb_strtoupper($row['headline'],'UTF-8'));
$rowCount++;
}
$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
header('Content-Type: application/vnd.ms-excel'); //mime type
header('Content-Disposition: attachment;filename="you-file-name.xlsx"'); //tell browser what's the file name
header('Cache-Control: max-age=0'); //no cache
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');

Joomla export Excel (.xls or .csv)

How to export the Excel (.csv or .xls) variable from database? It does not work to insert variable from database e.g. $temp (it can echo the single value from variable)
require_once(JPATH_LIBRARIES . '/phpexcel/library/PHPExcel.php');
require_once(JPATH_LIBRARIES.'/phpexcel/library/PHPExcel/IOFactory.php');$query = "SELECT referreid,insert_date,datareference FROM `miqi_alpha_userpoints_details` WHERE `referreid`='$referrerid' AND `enabled`='1' ORDER BY `insert_date` DESC";
$db->setQuery( $query );
$results = $db-> loadAssocList();
$temp = $results[0]['referreid'];
$objPHPExcel = new PHPExcel();
$objPHPExcel->getActiveSheet()->setCellValue('A1','123');
$objPHPExcel->getActiveSheet()->setCellValue('B1',$temp);
header('Content-Type: text/plain;charset=utf-8'); //mime type
header('Content-Disposition: attachment;filename="abc.csv"'); //tell browser what's the file name
header('Cache-Control: max-age=0'); //no cache
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'CSV');
$objWriter->save('php://output');
exit;

PHPExcel output unreadable and no errors thrown

Hello I have the following code
// 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");
$exchange = $_POST['exchange'];
$jobchange = $_POST['estimate'];
$wpchange = $_POST['wp'];
$username = "----";
$password = "----";
$hostname = "----";
$dbhandle = mysql_connect($hostname, $username, $password) or die("Unable to connect to MySQL");
$selected = mysql_select_db("----", $dbhandle) or die("Could not select examples");
$query = "SELECT * FROM btsec WHERE WP='$wpchange' AND Exchange='$exchange' AND Estimate='$jobchange'";
$result = mysql_query($query);
$acellnum = "3";
$bcellnum = "3";
$ccellnum = "3";
$dcellnum = "3";
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A1', 'Section ID')
->setCellValue('B1', 'Length')
->setCellValue('C1', 'Status')
->setCellValue('D1', 'TM');
while ($row = mysql_fetch_array($result)) {
// Query
// Add some data
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue("A".$acellnum, $row['SectionID'])
->setCellValue("B".$bcellnum, $row['Length'])
->setCellValue("C".$ccellnum, $row['Status'])
->setCellValue("D".$dcellnum, $row['TM']);
$acellnum++;
$bcellnum++;
$ccellnum++;
$dcellnum++;
}
// 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);
// 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;
It is generating the excel file, but all it outputs is text similar to this
ÐÏࡱá;þÿ
Opening in a text editor reveals no obvious errors and the script returns none either. I'm trying to output this to an Excel 2007 compatible format. Does anyone have any idea why this is happening?
EDIT: May not be relevant but Excel throws an error that the format does not match the extension
// Save Excel 2007 file
#echo date('H:i:s') . " Write to Excel2007 format\n";
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
ob_end_clean();
// We'll be outputting an excel file
header('Content-type: application/vnd.ms-excel');
// It will be called file.xls
header('Content-Disposition: attachment; filename="sectionlist.xlsx"');
$objWriter->save('php://output');
This fixed it and made it work! ob_end_clean was the solution.
To solve this problem try :
header('Content-Type: 'application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="test.xlsx"');
header('Cache-Control: max-age=0');
and
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
ob_end_clean();
ob_start();
$objWriter->save('php://output');
Try changing this:
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
to this:
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
Also, excel 2007 expects the file to be .xlsx so you should probably change that in your header statement.
My PhpExcel Library just stopped working properly.
The result excel file was all written with really weird characters.
This:
ob_end_clean();
was my solution too.
In recent PHP-versions PHPExcel stops working without any errors. Look in PHPExcel/Calculations/Functions.php at line 576: there is a break-command, which is not allowed by PHP. If you remove that line, all works as it should work.

PHPExcel: Download the Excel file on the client side

The problem was solved: For other users that may have this problem - notice the encoding of the PHP file. If you use PHPExcel it must be ANSII encoding and not UTF8, otherwise the EXCEL will be downloaded corruptly. The Headers that were added (answer 1) solved the problem after i changed the encoding of the file itself.
I am using PHPExcel in order to create an EXCEL from a table in MYSQL DB, so the user can download it to his computer.
The code bellow creates a correct Excel file but the problem is that it is downloaded to my server. I read in PHPExcel manual that i need to add headers:
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="'.$name.'.xls"');
header('Cache-Control: max-age=0');
header('Cache-Control: max-age=1');
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');
But if i do that, the downloaded file is:
1. Has some jibrish inside
2. Says that Excel needs to fix it because the file is not good.
The problem is that this file is saved as UTF8 and if i encode it as ANSI then it is working properly but of course it is a manual change and i need a working properly excel to reach the users.
What is the bug?
My code that works (but download the file to the server):
<?php
include 'connection.php';
include 'checkUser.php';
//Getting all the needed information from the DB
$task_id=$_GET['id'];
$query2 = "SELECT * FROM projects WHERE ProjectID=$task_id";
$data2 = mysqli_query($con, $query2);
$row = mysqli_fetch_array($data2);
$project_type = $row['ProjectType'];
$project_name = $row['ProjectName'];
switch ($project_type){
case 2: $NumberOfRows=22; $project = "slivedetails"; break;
case 3: $NumberOfRows=30; $project = "plivedetails"; break;
default: $NumberOfRows=0; $project = "none";
}
//column names
if ($project="slivedetails"){
$ColumnNames = mysqli_query($con,"SHOW COLUMNS FROM slivedetails") or die("mysql error");
}
else if ($project="plivedetails"){
$ColumnNames = mysqli_query($con, "SHOW COLUMNS FROM plivedetails") or die("mysql error");
}
$query = "SELECT * FROM $project WHERE TaskID=$task_id";
$data = mysqli_query($con, $query);
$num_rows = mysqli_num_rows($data);
/** Include PHPExcel */
require_once 'PHPExcel_1.7.9_doc/Classes/PHPExcel.php';
require_once 'PHPExcel_1.7.9_doc/Classes/PHPExcel/IOFactory.php';
// create new PHPExcel object
$objPHPExcel = new PHPExcel();
$objPHPExcel = new PHPExcel();
// writer already created the first sheet for us, let's get it
$objSheet = $objPHPExcel->getActiveSheet();
// rename the sheet
$objSheet->setTitle('Task Results');
// let's bold and size the header font and write the header
// as you can see, we can specify a range of cells, like here: cells from A1 to A4
$objSheet->getStyle('A1:AD1')->getFont()->setBold(true)->setSize(12);
$char = 65;
// write header]
for ($i=1;$i<=$NumberOfRows;$i++){
$col_name = mysqli_fetch_array($ColumnNames);
$objSheet->getCell(chr($char).'1')->setValue($col_name['Field']);
$char++;
}
// Now we need to get the data from the DB. While we have a row in the result:
$rowIterator=2; //our row number. We begin from 2 because the first one is the title.
while ($RowInfo = mysqli_fetch_array($data)){
//We will fill the information based on the amount of columns:
$char = 65; //we set the first char as column A
for ($i=0;$i<$NumberOfRows;$i++){
$objSheet->getCell(chr($char).$rowIterator)->setValue($RowInfo[$i]);
$char++;
}
$rowIterator++;
}
// autosize the columns
$char = 65;
for ($i=1;$i<=$NumberOfRows;$i++){
$objSheet->getColumnDimension(chr($char))->setAutoSize(true);
$char++;
}
// create the writer
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, "Excel2007");
$objWriter->save('results.xlsx');
?>
Remove the following inclusion:
require_once 'PHPExcel_1.7.9_doc/Classes/PHPExcel/IOFactory.php';
You declared the object twice. Remove one of them:
// create new PHPExcel object
$objPHPExcel = new PHPExcel();
Insert the following headers just before creating the Writer:
header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
header("Content-Disposition: attachment; filename=\"results.xlsx\"");
header("Cache-Control: max-age=0");
Instead of the following (which actually saves the file in the server):
$objWriter->save('results.xlsx');
Insert the following (which will create the downloadable file):
$objWriter->save("php://output");
This should solve the gibberish text. If you still get such text, insert the following code before the last line ($objWriter->save("php://output");):
ob_clean();
This worked for me. Hope it helps.
This should work, try to modify your code like this:
header("Content-Type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=my_excel_filename.xls");
header("Pragma: no-cache");
header("Expires: 0");
flush();
require_once 'PHPExcel.php';
$objPHPExcel = new PHPExcel();
// here fill data to your Excel sheet
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
Alex, I had the same problem. I did all of them but again result was the same. I just changed
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
to
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
and changed all .xlsx to .xls.
Hope It will help.
Download PHPExcel-1.8(from github) and replace it with the old PHPExcel.
Rename PHPExcel-1.8 to PHPExcel. In my code I have included require '../library/excel/PHPExcel.php';
I deleted all contents from this file (PHPExcel.php) and added only one line of code
require 'PHPExcel/Classes/PHPExcel.php';
(Note: I uploaded PHPExcel in the folder library/excel)
Works perfectly

Categories