PHP and excel export - php

I have problem of decimal places in excel 2013. The amount less than thousand it does not show the decimal otherwise show decimal in Excel cell. Amount with thousand show (1233.00) and if amount less than thousand then show (763).
$datatable = "<table><tr>";
while($nt=mysql_fetch_array($finalquery)) {
$amount= number_format($nt[3],2);
$datatable .= "<td>$amount</td>";
}
$datatable = "</tr></table>";
$dtimestamp= time( );
$ddatetime = date("G-i-s",$dtimestamp);
$filename = "External_data_" . date('dmY') .":". $ddatetime .".xls";
header('Content-type: application/ms-excel');
header("Content-Disposition: attachment; filename=\"" . $filename . "\"");
echo $datatable;

<?php //in moodle
mysql_connect($CFG->dbhost,$CFG->dbuser,$CFG->dbpass);
mysql_select_db($CFG->dbname);
$sql ="SELECT *
FROM dddd c WHERE a.deleted = 0 AND mi.is_deleted='0' AND a.id!='2' and a.regtype!='trial' AND ra.roleid=5 GROUP BY userid";
//$filename = $fname.".csv";
mysql_query("SET NAMES 'utf8'");
$rsSearchResults = mysql_query($sql) or die(mysql_error());
$xlsarr = array();
$xlshead = array();
$xls_lastcolumn='O';
$xl_aplha=createColumnsArray($xls_lastcolumn);
$nums=0;
for($i=0; $i<mysql_num_fields($rsSearchResults);$i++){
$column_name=mysql_fetch_field($rsSearchResults, $i);
$xlshead[$xl_aplha[$nums]]=$column_name->name;
$nums=$nums+1;
}
// $my_xlshead_add=array('15'=>'Registration Code');
// $_xlshead=array_merge($xlshead,$my_xlshead_add);
$xlsarr[] = $xlshead;
//$csvid=0;
while ($l = mysql_fetch_assoc($rsSearchResults)) {
$numk=0;
$l['Password']='';
if($l['Activation Date']=='1970-01-01')
{
$actdate='';
}
else
{
$actdate=date("Y/n/j",strtotime($l['Activation Date']));
}
$l['Activation Date'] = $actdate;
if($l['Expiration Date']=='1970-01-01')
{
$expdate='';
}
else
{
$expdate=date("Y/n/j",strtotime($l['Expiration Date']));
}
$l['Expiration Date'] = $expdate;
$reg_code=get_regcode($l['userid']);
// $my_array_add=array('15'=>$reg_code,'Registration Code'=>$reg_code);
// $_array_merge=array_merge($l,$my_array_add);
// unset($l['userid']);
// Dependent on select query
$xlsdata[$xl_aplha[$numk]]=$l['Coloumn4'];
$xlsdata[$xl_aplha[$numk=$numk+1]]=$l['Coloumn45'];
$xlsdata[$xl_aplha[$numk=$numk+1]]=$l['Coloumn4Name'];
$xlsdata[$xl_aplha[$numk=$numk+1]]=$l['Coloumn443'];
$xlsdata[$xl_aplha[$numk=$numk+1]]=$l['Coloumn4'];
$xlsdata[$xl_aplha[$numk=$numk+1]]=$l['Coloumn4Name'];
$xlsdata[$xl_aplha[$numk=$numk+1]]=$l['Coloumn5Address'];
$xlsdata[$xl_aplha[$numk=$numk+1]]=$l['Coloumn6Number'];
$xlsdata[$xl_aplha[$numk=$numk+1]]=$l['Coloumn7'];
$xlsdata[$xl_aplha[$numk=$numk+1]]=$l['Coloumn8'];
$xlsdata[$xl_aplha[$numk=$numk+1]]=$l['Coloumn9'];
$xlsdata[$xl_aplha[$numk=$numk+1]]=$l['Coloumn10Code'];
$xlsarr[]=$xlsdata;
// $csvid++;
}
// pr($xlsarr);
$fname = "Elsevier_Users";
//printExcel2($csvarr,"xls",$fname,false);
$myfilename=$fname.'.xls';
myprintExcel($xlsarr,$xls_lastcolumn,$myfilename);
?>///for excel import and export
function myprintExcel($xlsarr,$LastColumn,$filesname){
// global $CFG;
// require_once($CFG->libdir.'/phpmailer/class.phpmailer.php');
global $filePath;
ob_start();
include ($filePath.'/PHPExcel/Classes/PHPExcel.php');
$objPHPExcel = new PHPExcel();
$objPHPExcel->getProperties()->setCreator("XLSX")
->setLastModifiedBy("XLSX")
->setTitle("XLSX")
->setSubject("XLSX")
->setDescription("XLSX")
->setKeywords("XLSX")
->setCategory("ElsevierUsers");
// Add some data
$val=0;
//echo '<pre>';
//print_r($xlsarr);
//die();
foreach ($xlsarr as $arykey=>$aryLine)
{
$rowInd = $arykey+1;
$lastcol=createColumnsArray($LastColumn);
foreach ($lastcol as $key=>$char) {
// echo $aryLine[$i_count].$char.$arykey . "\n";
$objPHPExcel->setActiveSheetIndex(0)->setCellValue($char.$rowInd, $aryLine[$char]);
}
$val++;
}
$objPHPExcel->getActiveSheet()->setTitle('ElsevierUsers');
// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$objPHPExcel->setActiveSheetIndex(0);
// Query Database
// Redirect output to a client’s web browser (Excel5)
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="'.$filesname.'"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
exit;
}

Related

Custom Headers in PHP SQL Query

I have an html form that calls a php document on submit that downloads the values of a table as a csv file. My goal is to utilize the "as" within the select statement to achieve custom column headers within that document. For example, I would like to select tableNAME.address and print to the csv as "Site Location".
Here is a sample of the php along with a postgres query:
<?php
// show error messages
ini_set('error_reporting', E_ALL);
ini_set("display_errors", 1);
if( !empty($_SERVER['REQUEST_METHOD']) && (strcasecmp($_SERVER['REQUEST_METHOD'], 'post')===0) ) {
// Create connection
$conn = pg_connect("host=MYHOST port=ACCESS dbname=DBNAME user=USERNAME password=PWORD");
// Check connection
if (!$conn) {
echo "Did not connect.\n";
exit;
}
$result = pg_query($conn,
"
SELECT
tableNAME.address AS Address,
tableNAME.city AS City,
tableNAME.state_1 AS State,
-- adds 0's if zip code is not long enough
case length(tableNAME.zip)
WHEN 5 THEN tableNAME.zip
WHEN 4 THEN '0' || tableNAME.zip
WHEN 3 THEN '00' || tableNAME.zip
END AS Zip
FROM
db.tableNAME
WHERE
tableNAME.in_process = 'true' and
tableNAME.shippiing = 'false' and
tableNAME.soft_delete_id = '0' and
tableNAME.status_1 <> 'Closed' and
tableNAME.return_shipment = 'true'
ORDER BY
tableNAME.site_id asc;");
if (!$result) {
echo "Query failed.\n";
exit;
}
$num_fields = pg_num_fields($result);
$headers = array();
for ($i = 0; $i < $num_fields; $i++)
{
$headers[] = pg_field_name($result , $i);
}
$fp = fopen('php://output', 'w');
if ($fp && $result)
{
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="ups_returns.csv"');
header('Pragma: no-cache');
header('Expires: 0');
fputcsv($fp, $headers);
while ($row = pg_fetch_row($result))
{
fputcsv($fp, array_values($row));
}
die;
}
exit('It works');
}
?>
I have tried different variations on using apostrophe's within the select as statement. For example...
tableNAME.address as '""Site Location""'
tableNAME.address as 'Site Location'
tableNAME.address as '"Site Location"'
None of these have worked... I believe the line of my code that may need to be altered is:
$headers = array();
However, I have no idea what I can do to make it work.
Thanks
I have found a resolution... Instead of using data from the query to determine headers I set them manually.
$headers = array('Site Location','City','State','Zip','Package Type','Weight','ShippingCode','TicketNumber','ReturnService','Return','BillTo','Attention','SiteID','PrintLabel');
//for ($i = 0; $i < $num_fields; $i++)
//{
// $headers[] = pg_field_name($result , $i);
//}

how to use mysql while loop with xlsxwriter class?

I am using xlsxwriter but nothing work for me, I tried a dozen of things to transfer mysql database row data to excel row data but nothing worked :(
<?php
include_once("xlsxwriter.class.php");
include("connection.php");
ini_set('display_errors', 0);
ini_set('log_errors', 1);
error_reporting(E_ALL & ~E_NOTICE);
$filename = "PM.xlsx";
header('Content-disposition: attachment; filename="'.XLSXWriter::sanitize_filename($filename).'"');
header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate');
header('Pragma: public');
$rows = array();
$sql = "SELECT DATE_FORMAT(jobcard.Open_date_time,' %d-%b-%y') AS datee,vehicles_data.Frame_no, jobcard.Jobc_id,jobcard.serv_nature,jobcard.Customer_name,jobc_invoice.Lnet, jobc_invoice.Pnet, jobc_invoice.Snet, jobcard.Mileage,customer_data.cust_type,vehicles_data.model_year,jobcard.Veh_reg_no,jobcard.comp_appointed, customer_data.mobile,IF(variant_codes.Make IS NULL,'Others',variant_codes.Make) as make FROM `jobcard` LEFT OUTER JOIN jobc_invoice ON jobcard.Jobc_id=jobc_invoice.Jobc_id LEFT OUTER JOIN vehicles_data ON jobcard.Vehicle_id=vehicles_data.Vehicle_id LEFT OUTER JOIN variant_codes ON vehicles_data.Model=variant_codes.Model LEFT OUTER JOIN customer_data ON jobcard.Customer_id=customer_data.Customer_id ORDER BY `make` ASC";
$result=mysqli_query($conn,$sql) or die(mysqli_error($sql));
while($rowz = mysqli_fetch_row($result))
{
$rows[] = $rowz;
}
$writer = new XLSXWriter();
$writer->setAuthor('Some Author');
foreach($rows as $row)
$writer->writeSheetRow('Sheet1', $row);
$writer->writeToStdOut();
exit(0);
Even tried this, playing with arrays but nothing fruitful yet.
$row_excel=array();
$row_numb=0;
$writer = new XLSXWriter();
$writer->setAuthor('Some Author');
$result=mysqli_query($conn,$sql) or die(mysqli_error($sql));
while($row = mysqli_fetch_row($result))
{
$row_excel[$row_numb]=$row;
$writer->writeSheetRow('Sheet1', $row_excel[$row_numb]);
$row_numb++;
}
$writer->writeToStdOut();
exit(0);
try this:
while ($row = mysqli_fetch_row($result)) {
$data = array();
for ($i = 0; $i < mysqli_num_fields($result); $i++) {
$data[$i] = $row[$i];
}
$writer->writeSheetRow('Sheet1', $data);
}
$writer->writeToStdOut();
exit(0);
$data = array();
$result=mysqli_query($conn,$sql) or die(mysqli_error($sql));
while ($row = mysqli_fetch_row($result)) {
echo "<br/>";
for ($i = 0; $i < mysqli_num_fields($result); $i++) {
$data[$i] = $row[$i];
echo $row[$i];
}
}
I tried this code and it shows me data from database.
Hey I'm giving answer to bit old question but it may help someone if having same issue like #Rocky Rock and me.
Additionally I've to handle a large number of rows say 50,000 to 1,00,000. So I even tried some other solutions like chunking my result and tried to export into csv etc etc.
I also tried everything with force download with header and $writer->writeToStdOut(); but every logic goes into the vain.
But finally after day or two work around I coded as give and get rid of everything, believe me it can also download 1,00,000 rows in merely 20 seconds..
This is my code so instead of session variables of query and filename you can use whatever you like. Also I'd put some dummy variable as it is for one of our client.
<?php
include your required libraries..
include_once("lib/xlsxwriter.class.php");
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Download IDs</title>
</head>
<body>
<?php
$sqlsel = $_SESSION['rptQry'];
$ressql = mysqli_query($sqlsel);
$currentdt = date('Ymdhis');
$filename = $currentdt."_".$_SESSION['rptFileName'];
$header = array(
'Header1'=>'integer',
'Header 2'=>'integer',
'Header 3'=>'string',
'Header 4' =>'string'
);
$dataArray = array();
$writer = new XLSXWriter();
$writer->setAuthor('Adaptable Services');
$writer->writeSheetHeader('ExportedIDs', $header);
while($res = mysqli_fetch_array($ressql)){
$writer->writeSheetRow('Sheet1',$res);
}
$writer->writeToFile('/var/www/html/tmpxls/'.$filename);
echo '<script>location.href="www.example.com/tmpxls/'.$filename.'";</script>';
?>
</body>
</html>

PHPExcel memory exhausted when trying to make an excel file from records in mysql database. There are upto 20000 records needed to be copied

I have to export mysql database to an excel file. The number of records are very large (about 20000) when I was exporting the database, the server reported this fatal error:
failed to allocated 68 bytes.
Every time I run the script, the 68 bytes value changes to some new value like 33 bytes. My script is:
set_time_limit(0);
error_reporting(E_ALL);
ini_set('display_errors', '1');
ini_set("memory_limit", "1000M");
require_once("php_excel/PHPExcel.php");
require_once("php_excel/PHPExcel/IOFactory.php");
require_once("includes/config.php");
require_once("includes/functions/functions.php");
// Get The Field Name of equipments
$objPHPExcel = new PHPExcel();
$objPHPExcel->createSheet();
$objPHPExcel->setActiveSheetIndex(0);
//code to display headers
$activesheet=$objPHPExcel->getActiveSheet();
$result=exec_query("s...... ");
$num_fields = mysql_num_fields($result);
$X='A';
$columns=array();
$p=0;
for($i=0;$i<$num_fields;$i++)
{
$columns[]=mysql_field_name($result, $i);
$activesheet->setCellValue($X.'1', $columns[$p]);
$X++;$p++;
}
//second time....
$ts_id="";
$result=exec_query("........ ");
while($row=fetch_array($result))
{
if($ts_id!=$row['ts_id'])
{
$columns[]=$row['ts_id'];
$activesheet->setCellValue($X.'1', utf8_encode(explode(' ',$row['attribute_desc'])[0]).' Game');
$X++;$p++;
$ts_id=$row['ts_id'];
}
$columns[]=$row['attribute_desc'];
$activesheet->setCellValue($X.'1', $columns[$p]);
$X++;$p++;
$columns[]=$row['attribute_desc'];
$activesheet->setCellValue($X.'1', $columns[$p].' ok');
$X++;$p++;
}
//end of second....
$X='A';
$k=2;
//getting attribute ids
$result=exec_query("............s ");
$tsid=array();
$attribute=array();
while($row=fetch_array($result))
{
$attribute[]=$row['....._id'];
$tsid[]=$row['ts_id'];
}
//getting attribute ids end...
//filling values...
$result=exec_query("................");
$majorwordid=array();
while($row=fetch_array($result))
{
$majorwordid[]=$row['word_id'];
for($i=0;$i<$num_fields;$i++)
{
//echo $row[$columns[$i]]."<br>";
$activesheet->setCellValue($X.$k, utf8_encode($row[$columns[$i]]));
$X++;
}
$X='A';
$k++;
}
//audio number
$result=exec_query("...................");
$X='C';
$k=2;
while($row=fetch_array($result))
{
$activesheet->setCellValue($X.$k, utf8_encode($row['audio number']));
$k++;
}
//audio number ends...
//mait codesss
$X++;
$forid='';
for($a=0;$a<count($attribute);$a++)
{
$k=2;
if($forid!=$tsid[$a] ||$forid=='')
{
$result=exec_query(".............");
$word_ids=array();
while($row=fetch_array($result))
{
$word_ids[]=$row['word_id'];
}
for($i=0;$i<count($majorwordid);$i++)
{
if (in_array($majorwordid[$i], $word_ids)) {
$activesheet->setCellValue($X.$k,'1');
}
else
$activesheet->setCellValue($X.$k,' ');
$k++;
}
$forid=$tsid[$a];
$X++;
}
$k=2;
$result=exec_query("...............");
$word_ids=array();
while($row=fetch_array($result))
{
$word_ids[]=$row['word_id'];
}
for($i=0;$i<count($majorwordid);$i++)
{
if (in_array($majorwordid[$i], $word_ids)) {
$activesheet->setCellValue($X.$k,'1');
}
else
$activesheet->setCellValue($X.$k,' ');
$k++;
}
// for ok valuess....
$k=2;
$X++;
$result=exec_query("S............");
$word_ids=array();
while($row=fetch_array($result))
{
$word_ids[]=$row['word_id'];
}
for($i=0;$i<count($majorwordid);$i++)
{
if (in_array($majorwordid[$i], $word_ids)) {
$activesheet->setCellValue($X.$k,'1');
}
else
$activesheet->setCellValue($X.$k,' ');
$k++;
}
$X++;
}
$activesheet->setTitle('LexicoCMS');
$activesheet->getColumnDimension('S')->setWidth(140);
//second page...
$objPHPExcel->setActiveSheetIndex(1);
$activesheet1=$objPHPExcel->getActiveSheet();
$query="........";
$result=exec_query($query);
$num_fields = mysql_num_fields($result);
$X='A';
$columns=array();
$i=0;
for($i=0;$i<$num_fields;$i++)
{
$columns[]=mysql_field_name($result, $i);
$activesheet1->setCellValue($X.'1', utf8_encode($columns[$i]));
$X++;
}
$result=exec_query($query);
$num_fields = mysql_num_fields($result);
$X='A';
$k=2;
while($row=fetch_array($result))
{
for($i=0;$i<$num_fields;$i++)
{
$activesheet1->setCellValue($X.$k, utf8_encode($row[$columns[$i]]));
$X++;
}
$X='A';
$k++;
}
$activesheet1->setTitle('Other info');
$activesheet1->getColumnDimension('S')->setWidth(140);
//end of second page
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="Lexico_cms.xls"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
The issue is that you're keeping a large Excel object in memory, and your script just runs out of usable memory.
First you should try to determine if there are ways to reduce the memory consumption of your script, but if that fails you need to increase your PHP memory limit. In your php.ini file, locate the memory_limit setting that determines the maximum amount of memory a script may consume, e.g.
memory_limit = 64M;
Increase the value until you no longer see the error.

CSV file getting multiple records

I am exporting result of a query in a csv file. The code is as shown below:
$query = "SELECT DATE(punchdetails.punchin) as punchday,punchdetails.punchin,punchdetails.punchout,employeedetails.employeename
FROM punchdetails join(employeedetails) ON punchdetails.employeeid=employeedetails.employeeid
AND punchdetails.employeeid=$employeeid AND DATE(punchdetails.punchin)=$fromdate";
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");
ini_set('display_errors',1);
$private=1;
error_reporting(E_ALL ^ E_NOTICE);
$select_c = mysql_query($query);
while ($row = mysql_fetch_array($select_c))
{
$intime = strtotime($row['punchin']);
$mysqlintime = date( 'H:i:a', $intime );
$outtime = strtotime($row['punchout']);
$mysqlouttime = date( 'H:i:a', $outtime );
$result.=$row['employeename'].','.$row['punchday'].','.$mysqlintime.','.$mysqlouttime;
$result.="\n";
echo $result;
}
When I execute the query it is returning records correctly. But when I download the result of the query as csv file, the records are getting duplicated. I am getting the resultant csv file data as shown below:
Sonu,2013-09-26,10:55:am,11:12:am
Sonu,2013-09-26,10:55:am,11:12:am
Kristo,2013-09-26,11:23:am,11:24:am
I am not getting what is the problem. Can anybody help me to solve this? Thanks in advance.
I see the problem
you concatinate the result with each row, then echo. So, each time you echo - you will echo all the previous results + the current result.
Either, change:
$result.=$row['employeename'].','.$row['punchday'].','.$mysqlintime.','.$mysqlouttime;
$result.="\n";
to:
echo $row['employeename'].','.$row['punchday'].','.$mysqlintime.','.$mysqlouttime;
echo "\n";
or move the echo $result; outside the while loop
You need to echo $result outside of the while loop:
$result='';
while ($row = mysql_fetch_array($select_c))
{
$intime = strtotime($row['punchin']);
$mysqlintime = date( 'H:i:a', $intime );
$outtime = strtotime($row['punchout']);
$mysqlouttime = date( 'H:i:a', $outtime );
$result.=$row['employeename'].','.$row['punchday'].','.$mysqlintime.','.$mysqlouttime;
$result.="\n";
}
echo $result;

How to export data to an excel file using PHPExcel

I have taken the source code from limesurvey and have added the PHPExcel library to my limesurvey code to export data to an excel file after you click a link. Currently the excel file opens with some dummy data in it with no problems. I need to be able to add data dynamically from the web server after a user types in survey information. I have looked into some sites I have found but I havent had much luck. Can anyone help me out?
EDIT
<?php
$dbhost= "mysql"; //your MySQL Server
$dbuser = "survey"; //your MySQL User Name
$dbpass = "password"; //your MySQL Password
$dbname = "database";
//your MySQL Database Name of which database to use this
$tablename = "questions"; //your MySQL Table Name which one you have to create excel file
// your mysql query here , we can edit this for your requirement
$sql = "Select * from $table ";
//create code for connecting to mysql
$Connect = #mysql_connect($dbhost, $dbuser, $dbpass)
or die("Couldn't connect to MySQL:<br>" . mysql_error() . "<br>" . mysql_errno());
//select database
$Db = #mysql_select_db($dbname, $Connect)
or die("Couldn't select database:<br>" . mysql_error(). "<br>" . mysql_errno());
//execute query
$result = #mysql_query($sql,$Connect)
or die("Couldn't execute query:<br>" . mysql_error(). "<br>" . mysql_errno());
error_reporting(E_ALL);
require_once '../Classes/PHPExcel.php';
$objPHPExcel = new PHPExcel();
// Set the active Excel worksheet to sheet 0
$objPHPExcel->setActiveSheetIndex(0);
// Initialise the Excel row number
$rowCount = 1;
//start of printing column names as names of MySQL fields
$column = 'A';
for ($i = 1; $i < mysql_num_fields($result); $i++)
{
$objPHPExcel->getActiveSheet()->setCellValue($column.$rowCount, mysql_field_name($result,$i));
$column++;
}
//end of adding column names
//start while loop to get data
$rowCount = 2;
while($row = mysql_fetch_row($result))
{
$column = 'A';
for($j=1; $j<mysql_num_fields($result);$j++)
{
if(!isset($row[$j]))
$value = NULL;
elseif ($row[$j] != "")
$value = strip_tags($row[$j]);
else
$value = "";
$objPHPExcel->getActiveSheet()->setCellValue($column.$rowCount, $value);
$column++;
}
$rowCount++;
}
// Redirect output to a client’s web browser (Excel5)
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="results.xls"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
If you've copied this directly, then:
->setCellValue('B2', Ackermann')
should be
->setCellValue('B2', 'Ackermann')
In answer to your question:
Get the data that you want from limesurvey, and use setCellValue() to store those data values in the cells where you want to store it.
The Quadratic.php example file in /Tests might help as a starting point: it takes data from an input form and sets it to cells in an Excel workbook.
EDIT
An extremely simplistic example:
// Create your database query
$query = "SELECT * FROM myDataTable";
// Execute the database query
$result = mysql_query($query) or die(mysql_error());
// Instantiate a new PHPExcel object
$objPHPExcel = new PHPExcel();
// Set the active Excel worksheet to sheet 0
$objPHPExcel->setActiveSheetIndex(0);
// Initialise the Excel row number
$rowCount = 1;
// Iterate through each result from the SQL query in turn
// We fetch each database result row into $row in turn
while($row = mysql_fetch_array($result)){
// Set cell An to the "name" column from the database (assuming you have a column called name)
// where n is the Excel row number (ie cell A1 in the first row)
$objPHPExcel->getActiveSheet()->SetCellValue('A'.$rowCount, $row['name']);
// Set cell Bn to the "age" column from the database (assuming you have a column called age)
// where n is the Excel row number (ie cell A1 in the first row)
$objPHPExcel->getActiveSheet()->SetCellValue('B'.$rowCount, $row['age']);
// Increment the Excel row counter
$rowCount++;
}
// Instantiate a Writer to create an OfficeOpenXML Excel .xlsx file
$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
// Write the Excel file to filename some_excel_file.xlsx in the current directory
$objWriter->save('some_excel_file.xlsx');
EDIT #2
Using your existing code as the basis
// Instantiate a new PHPExcel object
$objPHPExcel = new PHPExcel();
// Set the active Excel worksheet to sheet 0
$objPHPExcel->setActiveSheetIndex(0);
// Initialise the Excel row number
$rowCount = 1;
//start of printing column names as names of MySQL fields
$column = 'A';
for ($i = 1; $i < mysql_num_fields($result); $i++)
{
$objPHPExcel->getActiveSheet()->setCellValue($column.$rowCount, mysql_field_name($result,$i));
$column++;
}
//end of adding column names
//start while loop to get data
$rowCount = 2;
while($row = mysql_fetch_row($result))
{
$column = 'A';
for($j=1; $j<mysql_num_fields($result);$j++)
{
if(!isset($row[$j]))
$value = NULL;
elseif ($row[$j] != "")
$value = strip_tags($row[$j]);
else
$value = "";
$objPHPExcel->getActiveSheet()->setCellValue($column.$rowCount, $value);
$column++;
}
$rowCount++;
}
// Redirect output to a client’s web browser (Excel5)
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="Limesurvey_Results.xls"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
Try the below complete example for the same
<?php
$objPHPExcel = new PHPExcel();
$query1 = "SELECT * FROM employee";
$exec1 = mysql_query($query1) or die ("Error in Query1".mysql_error());
$serialnumber=0;
//Set header with temp array
$tmparray =array("Sr.Number","Employee Login","Employee Name");
//take new main array and set header array in it.
$sheet =array($tmparray);
while ($res1 = mysql_fetch_array($exec1))
{
$tmparray =array();
$serialnumber = $serialnumber + 1;
array_push($tmparray,$serialnumber);
$employeelogin = $res1['employeelogin'];
array_push($tmparray,$employeelogin);
$employeename = $res1['employeename'];
array_push($tmparray,$employeename);
array_push($sheet,$tmparray);
}
header('Content-type: application/vnd.ms-excel');
header('Content-Disposition: attachment; filename="name.xlsx"');
$worksheet = $objPHPExcel->getActiveSheet();
foreach($sheet as $row => $columns) {
foreach($columns as $column => $data) {
$worksheet->setCellValueByColumnAndRow($column, $row + 1, $data);
}
}
//make first row bold
$objPHPExcel->getActiveSheet()->getStyle("A1:I1")->getFont()->setBold(true);
$objPHPExcel->setActiveSheetIndex(0);
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save(str_replace('.php', '.xlsx', __FILE__));
?>
$this->load->library('excel');
$file_name = 'Demo';
$arrHeader = array('Name', 'Mobile');
$arrRows = array(0=>array('Name'=>'Jayant','Mobile'=>54545), 1=>array('Name'=>'Jayant1', 'Mobile'=>44454), 2=>array('Name'=>'Jayant2','Mobile'=>111222), 3=>array('Name'=>'Jayant3', 'Mobile'=>99999));
$this->excel->getActiveSheet()->fromArray($arrHeader,'','A1');
$this->excel->getActiveSheet()->fromArray($arrRows);
header('Content-Type: application/vnd.ms-excel'); //mime type
header('Content-Disposition: attachment;filename="'.$file_name.'"'); //tell browser what's the file name
header('Cache-Control: max-age=0'); //no cache
$objWriter = PHPExcel_IOFactory::createWriter($this->excel, 'Excel5');
$objWriter->save('php://output');
Work 100%. maybe not relation to creator answer but i share it for users have a problem with export mysql query to excel with phpexcel.
Good Luck.
require('../phpexcel/PHPExcel.php');
require('../phpexcel/PHPExcel/Writer/Excel5.php');
$filename = 'userReport'; //your file name
$objPHPExcel = new PHPExcel();
/*********************Add column headings START**********************/
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A1', 'username')
->setCellValue('B1', 'city_name');
/*********************Add data entries START**********************/
//get_result_array_from_class**You can replace your sql code with this line.
$result = $get_report_clas->get_user_report();
//set variable for count table fields.
$num_row = 1;
foreach ($result as $value) {
$user_name = $value['username'];
$c_code = $value['city_name'];
$num_row++;
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A'.$num_row, $user_name )
->setCellValue('B'.$num_row, $c_code );
}
/*********************Autoresize column width depending upon contents START**********************/
foreach(range('A','B') as $columnID) {
$objPHPExcel->getActiveSheet()->getColumnDimension($columnID)->setAutoSize(true);
}
$objPHPExcel->getActiveSheet()->getStyle('A1:B1')->getFont()->setBold(true);
//Make heading font bold
/*********************Add color to heading START**********************/
$objPHPExcel->getActiveSheet()
->getStyle('A1:B1')
->getFill()
->setFillType(PHPExcel_Style_Fill::FILL_SOLID)
->getStartColor()
->setARGB('99ff99');
$objPHPExcel->getActiveSheet()->setTitle('userReport'); //give title to sheet
$objPHPExcel->setActiveSheetIndex(0);
header('Content-Type: application/vnd.ms-excel');
header("Content-Disposition: attachment;Filename=$filename.xls");
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
I currently use this function in my project after a series of googling to download excel file from sql statement
// $sql = sql query e.g "select * from mytablename"
// $filename = name of the file to download
function queryToExcel($sql, $fileName = 'name.xlsx') {
// initialise excel column name
// currently limited to queries with less than 27 columns
$columnArray = array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z");
// Execute the database query
$result = mysql_query($sql) or die(mysql_error());
// Instantiate a new PHPExcel object
$objPHPExcel = new PHPExcel();
// Set the active Excel worksheet to sheet 0
$objPHPExcel->setActiveSheetIndex(0);
// Initialise the Excel row number
$rowCount = 1;
// fetch result set column information
$finfo = mysqli_fetch_fields($result);
// initialise columnlenght counter
$columnlenght = 0;
foreach ($finfo as $val) {
// set column header values
$objPHPExcel->getActiveSheet()->SetCellValue($columnArray[$columnlenght++] . $rowCount, $val->name);
}
// make the column headers bold
$objPHPExcel->getActiveSheet()->getStyle($columnArray[0]."1:".$columnArray[$columnlenght]."1")->getFont()->setBold(true);
$rowCount++;
// Iterate through each result from the SQL query in turn
// We fetch each database result row into $row in turn
while ($row = mysqli_fetch_array($result, MYSQL_NUM)) {
for ($i = 0; $i < $columnLenght; $i++) {
$objPHPExcel->getActiveSheet()->SetCellValue($columnArray[$i] . $rowCount, $row[$i]);
}
$rowCount++;
}
// set header information to force download
header('Content-type: application/vnd.ms-excel');
header('Content-Disposition: attachment; filename="' . $fileName . '"');
// Instantiate a Writer to create an OfficeOpenXML Excel .xlsx file
// Write the Excel file to filename some_excel_file.xlsx in the current directory
$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
// Write the Excel file to filename some_excel_file.xlsx in the current directory
$objWriter->save('php://output');
}
// gl and gl2 excel file Export Program
public function glExcelFileExport()
{
$from_date1 = $this->input->post('from_date1');
$to_date1 = $this->input->post('to_date1');
$account_number = $this->input->post('account_number');
$glnames = $this->input->post('glnames');
$sql = "SELECT * FROM ut_sbi_reco_rungl WHERE value_date between '".$from_date1."' AND '".$to_date1."' ";
$result = $this->db->query($sql)->result_array();
if(count($result)>0)
{
require FCPATH . 'vendor/autoload.php';
$object = new PHPExcel();
$prestasi = $object->setActiveSheetIndex(0);
//manage row hight
$object->getActiveSheet()->getRowDimension(1)->setRowHeight(25);
// Excel Heading Description
if($glnames == 'gl1') {
//style alignment
$styleArray = array(
'alignment' => array('horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER,
),
);
$object->getActiveSheet()->getStyle('A1:U1')->getFont()->setBold(true);
$object->getActiveSheet()->getStyle('A1:U1')->applyFromArray($styleArray);
//border
$styleArray1 = array(
'borders' => array(
'allborders' => array(
'style' => PHPExcel_Style_Border::BORDER_THIN
)
)
);
//background
$styleArray12 = array(
'fill' => array(
'type' => PHPExcel_Style_Fill::FILL_SOLID,
'startcolor' => array(
'rgb' => 'FFFF00',
),
),
);
//freeepane
$object->getActiveSheet()->freezePane('A2');
//column width
$object->getActiveSheet()->getColumnDimension('A')->setWidth(15);
$object->getActiveSheet()->getColumnDimension('B')->setWidth(15);
$object->getActiveSheet()->getColumnDimension('C')->setWidth(15);
$object->getActiveSheet()->getColumnDimension('D')->setWidth(20);
$object->getActiveSheet()->getColumnDimension('E')->setWidth(20);
$object->getActiveSheet()->getColumnDimension('F')->setWidth(12);
$object->getActiveSheet()->getColumnDimension('G')->setWidth(15);
$object->getActiveSheet()->getColumnDimension('H')->setWidth(20);
$object->getActiveSheet()->getColumnDimension('I')->setWidth(20);
$object->getActiveSheet()->getColumnDimension('J')->setWidth(20);
$object->getActiveSheet()->getColumnDimension('K')->setWidth(20);
$object->getActiveSheet()->getColumnDimension('L')->setWidth(10);
$object->getActiveSheet()->getColumnDimension('M')->setWidth(12);
$object->getActiveSheet()->getColumnDimension('N')->setWidth(25);
$object->getActiveSheet()->getColumnDimension('O')->setWidth(15);
$object->getActiveSheet()->getColumnDimension('P')->setWidth(15);
$object->getActiveSheet()->getColumnDimension('Q')->setWidth(15);
$object->getActiveSheet()->getColumnDimension('R')->setWidth(15);
$object->getActiveSheet()->getColumnDimension('S')->setWidth(15);
$object->getActiveSheet()->getColumnDimension('T')->setWidth(25);
$object->getActiveSheet()->getColumnDimension('U')->setWidth(15);
$object->getActiveSheet()->getStyle('A1:U1')->applyFromArray($styleArray1);
$object->getActiveSheet()->getStyle('A1:U1')->applyFromArray($styleArray12);
$object->getActiveSheet()->getStyle('I')->getNumberFormat()->setFormatCode("0.00");
$table_columns = array("SRL", "Scheme", "Tran Type", "App Refer", "OTH Refer",
"Account", "Name", "Value Date", "Amount", "Pay Category", "Rev Flg",
"Security", "Cheque Number", "SCH", "Book Date", "Cheque Date",
"Reg Id", "Inputter", "Narration", "FL", "Batch Number");
$column = 0;
foreach($table_columns as $field)
{
$object->getActiveSheet()->setCellValueByColumnAndRow($column, 1, $field);
$column++;
}
}
if($glnames == 'gl2') {
//style alignment
$styleArray = array(
'alignment' => array('horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER,
),
);
$object->getActiveSheet()->getStyle('A1:C1')->getFont()->setBold(true);
$object->getActiveSheet()->getStyle('A1:C1')->applyFromArray($styleArray);
//border
$styleArray1 = array(
'borders' => array(
'allborders' => array(
'style' => PHPExcel_Style_Border::BORDER_THIN
)
)
);
//background
$styleArray12 = array(
'fill' => array(
'type' => PHPExcel_Style_Fill::FILL_SOLID,
'startcolor' => array(
'rgb' => 'FFFF00',
),
),
);
//freeepane
$object->getActiveSheet()->freezePane('A2');
//column width
$object->getActiveSheet()->getColumnDimension('A')->setWidth(15);
$object->getActiveSheet()->getColumnDimension('B')->setWidth(15);
$object->getActiveSheet()->getColumnDimension('C')->setWidth(15);
$object->getActiveSheet()->getStyle('A1:C1')->applyFromArray($styleArray1);
$object->getActiveSheet()->getStyle('A1:C1')->applyFromArray($styleArray12);
$object->getActiveSheet()->getStyle('C')->getNumberFormat()->setFormatCode("0.00");
$table_columns1 = array("Account", "Name", "Amount");
$column1 = 0;
foreach($table_columns1 as $field1)
{
$object->getActiveSheet()->setCellValueByColumnAndRow($column1, 1, $field1);
$column1++;
}
}
// List of column names
$style = array(
'alignment' => array(
'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
)
);
$prestasi->getDefaultStyle()->applyFromArray($style);
if($glnames == 'gl1') {
// Gl1 Query
$excel_row = 2;
for ($kk=0;$kk<count($account_number);$kk++)
{
$account_number2 = $account_number[$kk];
$gl1Arr = $this->ut_gl_model->getDisplayGl1Query($account_number2,$from_date1,$to_date1);
foreach($gl1Arr as $row)
{
$object->getActiveSheet()->setCellValueByColumnAndRow(0, $excel_row, $row['srl']);
$object->getActiveSheet()->setCellValueByColumnAndRow(1, $excel_row, $row['scheme']);
$object->getActiveSheet()->setCellValueByColumnAndRow(2, $excel_row, $row['tran_type']);
$object->getActiveSheet()->setCellValueByColumnAndRow(3, $excel_row, $row['app_refer']);
$object->getActiveSheet()->setCellValueByColumnAndRow(4, $excel_row, $row['oth_refer']);
$object->getActiveSheet()->setCellValueByColumnAndRow(5, $excel_row, $row['account']);
$object->getActiveSheet()->setCellValueByColumnAndRow(6, $excel_row, $row['name']);
$object->getActiveSheet()->setCellValueByColumnAndRow(7, $excel_row, (isset($row['value_date']) && $row['value_date']!='0000-00-00')?date('d/m/Y',strtotime($row['value_date'])):'');
$object->getActiveSheet()->setCellValueByColumnAndRow(8, $excel_row, $row['amt']);
$object->getActiveSheet()->setCellValueByColumnAndRow(9, $excel_row, $row['pay_catego']);
$object->getActiveSheet()->setCellValueByColumnAndRow(10, $excel_row, $row['rev_flg']);
$object->getActiveSheet()->setCellValueByColumnAndRow(11, $excel_row, $row['security']);
$object->getActiveSheet()->setCellValueByColumnAndRow(12, $excel_row, $row['chq_number']);
$object->getActiveSheet()->setCellValueByColumnAndRow(13, $excel_row, 'y');
$object->getActiveSheet()->setCellValueByColumnAndRow(14, $excel_row, (isset($row['book_date']) && $row['book_date']!='0000-00-00')?date('d/m/Y',strtotime($row['book_date'])):'');
$object->getActiveSheet()->setCellValueByColumnAndRow(15, $excel_row, (isset($row['chq_date']) && $row['chq_date']!='0000-00-00')?date('d/m/Y',strtotime($row['chq_date'])):'');
$object->getActiveSheet()->setCellValueByColumnAndRow(16, $excel_row, $row['reg_id']);
$object->getActiveSheet()->setCellValueByColumnAndRow(17, $excel_row, $row['inputter']);
$object->getActiveSheet()->setCellValueByColumnAndRow(18, $excel_row, $row['narration']);
$object->getActiveSheet()->setCellValueByColumnAndRow(19, $excel_row, '');
$object->getActiveSheet()->setCellValueByColumnAndRow(20, $excel_row, '');
$excel_row++;
}
}
// Excel Download Logic
$downloadFile = 'gl1_'.date('Ymd').'.xlsx';
$prestasi->setTitle("Gl1 Dump");
$object_writer = PHPExcel_IOFactory::createWriter($object, 'Excel2007');
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="'.$downloadFile.'" ');
$object_writer->save('php://output');
}
$excel_row1 = 2;
if($glnames == 'gl2') {
// Gl2 Query
for ($jj=0;$jj<count($account_number);$jj++)
{
$account_number3 = $account_number[$jj];
$gl2Arr = $this->ut_gl_model->getDisplayGl2Query($account_number3,$from_date1,$to_date1);
foreach($gl2Arr as $row1)
{
$object->getActiveSheet()->setCellValueByColumnAndRow(0, $excel_row1, $row1['account']);
$object->getActiveSheet()->setCellValueByColumnAndRow(1, $excel_row1, $row1['name']);
$object->getActiveSheet()->setCellValueByColumnAndRow(2, $excel_row1, $row1['amount']);
// $object->getActiveSheet()->setCellValueByColumnAndRow(3, $excel_row1, $row1['value_date']);
$excel_row1++;
}
}
// Excel Download Logic
$prestasi->setTitle("Gl2 Dump");
$downloadFile2 = 'gl2_'.date('Ymd').'.xlsx';
$object_writer = PHPExcel_IOFactory::createWriter($object, 'Excel2007');
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="'.$downloadFile2.'" ');
$object_writer->save('php://output');
}
}
else
{
$this->session->set_flashdata('error', 'Data not found.');
redirect(site_url('sbi-reco/run-gl'));
}
}

Categories