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 ?
Related
I am uploading a excel file, reading the contents and writing to a new excel file using phpspreadsheet.
I am trying to create a excel file.
I am writing into cells using the following code
$writesheet->setActiveSheetIndex(0)->setCellValue('A1','myemail#gmail.com');
these lines
echo 'valid';
echo $cell;
echo $toemail;
print all the values correctly.
But this line of code is not working..
Full code:
<?php
include '../includes/common.php';
include "class.emailvalidator.php";
/////////////////////////////////////EXCEL READER ////////////////////////////////
if(!empty($_FILES)){
require 'spreadsheet/vendor/autoload.php';
$file = $_FILES['files']['tmp_name'];
$file_name = $_FILES['files']['name'];
$upload_path = 'files/'.$file_name;
if(move_uploaded_file($file,$upload_path)){
$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($upload_path);
$worksheet = $spreadsheet->getActiveSheet();
$highestRow = $worksheet->getHighestRow();
for ($row = 1; $row <= $highestRow; ++$row) {
$toemail = $worksheet->getCellByColumnAndRow(1, $row)->getValue();
$fromemail = 'admin#myimsuite.com';
$details = verifyEmail($fromemail,$toemail,true);
$writesheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
$cell = 'A'.$row;
if($details[0]== 'valid'){
echo 'valid';
echo $cell;
echo $toemail;
$writesheet->setActiveSheetIndex(0)->setCellValue($cell, $toemail);
}elseif($details[0]== 'invalid'){
}
}
if(file_exists($upload_path)){
unlink($upload_path);
}
$writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($writesheet);
$fxls ='excel-file_1.xlsx';
$writer->save($fxls);
if(file_exists($fxls)){
//force_download($fxls);
}
}
die();
}
function force_download($filename) {
$filedata = #file_get_contents($filename);
// SUCCESS
if ($filedata)
{
// GET A NAME FOR THE FILE
$basename = basename($filename);
// THESE HEADERS ARE USED ON ALL BROWSERS
header("Content-Type: application-x/force-download");
header("Content-Disposition: attachment; filename=$basename");
header("Content-length: " . (string)(strlen($filedata)));
header("Expires: ".gmdate("D, d M Y H:i:s", mktime(date("H")+2, date("i"), date("s"), date("m"), date("d"), date("Y")))." GMT");
header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
// THIS HEADER MUST BE OMITTED FOR IE 6+
if (FALSE === strpos($_SERVER["HTTP_USER_AGENT"], 'MSIE '))
{
header("Cache-Control: no-cache, must-revalidate");
}
// THIS IS THE LAST HEADER
header("Pragma: no-cache");
// FLUSH THE HEADERS TO THE BROWSER
flush();
// CAPTURE THE FILE IN THE OUTPUT BUFFERS - WILL BE FLUSHED AT SCRIPT END
ob_start();
echo $filedata;
}
// FAILURE
else
{
die("ERROR: UNABLE TO OPEN $filename");
}
}
/////////////////////////////////////EXCEL READER ////////////////////////////////
////////////////////////Email Related//////////////////////////////
//var_dump($log);
////////////////////////End Email Related//////////////////////////////
$objSmarty->assign("page",'bannerindex');
$objSmarty->setTemplateDir("../templates");
$objSmarty->display("email_validator.tpl");
?>
Try running $writer->setPreCalculateFormulas(false); - fixed it for me
I am trying to export data from a html table to an excel file using phpExcel. The issue I am having is that I cannot seem to get the data through to it.
I have the following jquery code which runs on a button press to get the data out of the table and post it to the php code.
export data jquery
function storeTblValues()
{
var tableData = new Array();
$('#LogsTable tr').each(function(row, tr)
{
if(row == 0) //Table Headers
{
tableData[row] =
{
"LogDate" : $(tr).find('th:eq(0)').text(),
"LogType" : $(tr).find('th:eq(1)').text(),
"StartTime" : $(tr).find('th:eq(2)').text(),
"FinishTime" : $(tr).find('th:eq(3)').text(),
"Duration" : $(tr).find('th:eq(4)').text()
}
}
else //Table data
{
tableData[row] =
{
"LogDate" : $(tr).find('td:eq(0)').text(),
"LogType" : $(tr).find('td:eq(1)').text(),
"StartTime" : $(tr).find('td:eq(2)').text(),
"FinishTime" : $(tr).find('td:eq(3)').text(),
"Duration" : $(tr).find('td:eq(4)').text(),
}
}
});
return tableData;
}
function exportToExcel()
{
var tableData;
tableData = $.toJSON(storeTblValues());
var tmp = "pTableData=" + tableData;
$.ajax({
type: 'POST',
url: 'create_export_files.php',
data : tmp,
success : function(data)
{
window.location = 'create_export_files.php';
}
});
}
Top bit of the php file receiving the data
Create_export_files.php
$tableData = "";
if (isset($_POST["pTableData"]))
{
$tableData = $_POST["pTableData"];
$tableData = json_decode($tableData, TRUE);
}
else
{
$tableData = "empty";
}
generateExcel($tableData);
function generateExcel($tableData)
{
/** Include PHPExcel */
require_once dirname(__FILE__) . '/../Classes/PHPExcel.php';
// Create new PHPExcel object
$objPHPExcel = new PHPExcel();
// Add some data
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A1', 'hello')
->setCellValue('B2', 'world!')
->setCellValue('C1', 'Hello')
->setCellValue('D2', 'world!');
// 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);
$filename = 'export '.date('d-m-Y h:i:a').'.xlsx';
// 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');
}
I always seem to be going into the else part of the statement. Where am I going wrong?
If I remove the isset bit around the pTableData then the file gets created but is corrupted. Opening it in notepad++ I can see it says pTableData is undefined. Is that because the php file gets run again to make the file download?
try this code:
<?php
$str = "<table>
<tr><td>a</td><td>b</td></tr>
<tr><td>a</td><td>b</td></tr>
<tr><td>a</td><td>b</td></tr>
<tr><td>a</td><td>b</td></tr>
</table>
";
file_put_contents("table.xls",$str);
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
Just curious about the requirements for the whole PHPExcel project when you want to create a simple dynamically generated Excel file that doesn't exceed more than 125 lines , i'm generating a report of names and stats that go along with these names on my site, although it takes around 15-20 seconds to generate it after you click the button, which is far too long.
Just wondering if you need the whole project to do this or can you(so to speak)trim the fat to make it quicker ?
Any help would be much appreciated
$this->_helper->layout()->disableLayout();
$data = Factory_Company::getForAdminCompaniesPage(array(
"pageSize" => 10000,
"page" => 0
));
$objPHPExcel = new PHPExcel();
$objPHPExcel->getActiveSheet()->getStyle("A1:J1")->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->setAutoFilter('A1:A1');
$objPHPExcel->getProperties()->setCreator("Stackover")
->setLastModifiedBy("john smith")
->setTitle("Test Agency List")
->setSubject("Test Agency List")
->setDescription("Test Agency List")
->setKeywords("Test Agency Excel List")
->setCategory("Test Agency");
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A1', 'Agency')
->setCellValue('B1', 'Date Added')
->setCellValue('C1', '# of jobs')
->setCellValue('D1', '# of candidates')
->setCellValue('E1', 'Location')
->setCellValue('F1', 'Email')
->setCellValue('G1', 'Contact Name')
->setCellValue('H1', 'Last Logged in')
->setCellValue('I1', 'Sales Rep')
->setCellValue('J1', 'Active/Inactive');
$rowID = 2;
foreach ($data as $rowArray) {
$columnID = 'A';
foreach ($rowArray as $columnValue) {
$objPHPExcel->getActiveSheet()->setCellValue($columnID . $rowID, $columnValue);
$columnID++;
}
$rowID++;
}
$objPHPExcel->getActiveSheet()->setTitle('Intalex Agency List');
$objPHPExcel->setActiveSheetIndex(0);
// Redirect output to a client’s web browser (Excel2007)
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="Agencies.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');
}
}
You can eliminate the nested foreach loop by changing
foreach ($data as $rowArray) {
$columnID = 'A';
foreach ($rowArray as $columnValue) {
$objPHPExcel->getActiveSheet()->setCellValue($columnID . $rowID, $columnValue);
$columnID++;
}
$rowID++;
}
to
foreach ($data as $rowArray) {
$objPHPExcel->getActiveSheet()->fromArray($rowArray, null, 'A'. $rowID++);
}
or even simply
$objPHPExcel->getActiveSheet()->fromArray($data, null, 'A2');
And eliminate
$objPHPExcel->getActiveSheet()->setAutoFilter('A1:A1');
because it's meaningless setting autofiltering on a single cell, but will add overhead
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++;
}