I have the task of generating the excel sheet of each and every student separately so I used PHPExcel lib to perform the task
<?php
$host='localhost'; $user='root'; $pass=''; $DataBase='college';//define the correct values
// open the connexion to the databases server
$Link=#mysqli_connect($host,$user,$pass,$DataBase) or die('Can\'t connect !');
mysqli_set_charset($Link, 'utf8');//if not by default
//your request
if(isset($_GET['stud_id'])){
$id=$_GET['stud_id'];
$SQL='SELECT * from stud_master where stud_id=$id';
$rs=mysqli_query($Link, $SQL);//get the result (ressource)
/** Include PHPExcel */
require_once 'ec/Classes/PHPExcel.php';//change if necessary
// Create new PHPExcel object
$objPHPExcel = new PHPExcel();
$F=$objPHPExcel->getActiveSheet();
$Line=1;
while($Trs=mysqli_fetch_assoc($rs)){//extract each record
$F->
setCellValue('A'.$Line, $Trs['stud_id'])->
setCellValue('B'.$Line, $Trs['course_id'])->
setCellValue('C'.$Line, $Trs['fname'])->
setCellValue('D'.$Line, $Trs['mname'])->
setCellValue('E'.$Line, $Trs['lname']);//write in the sheet
++$Line;
}
}
// Redirect output to a client’s web browser (Excel5)
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="report.xls"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
exit;
Seems, the you have an error in your SQL syntax:
//use double quotes here, not single - otherwise $id won't be substituted
$SQL = "SELECT * from stud_master where stud_id=$id";
$rs=mysqli_query($Link, $SQL);//get the result (ressource)
But better use prepared statements to protect from SQL injection.
Related
I'm attempting to download a spreadsheet using PHPExcel but so far nothing but a blank page.
$items = array("test 1", "test 2", "test 3");
/** PHPExcel */
require_once dirname(__FILE__) . '/../../Classes/PHPExcel.php';
// Create new PHPExcel object
//echo date('H:i:s') . " Create new PHPExcel object\n";
$objPHPExcel = new PHPExcel();
// Set properties
$objPHPExcel->getProperties()->setCreator("User 1");
$objPHPExcel->getProperties()->setLastModifiedBy("User 1");
$objPHPExcel->getProperties()->setTitle(" Quotes");
$objPHPExcel->getProperties()->setSubject("Quotes");
$objPHPExcel->getProperties()->setDescription("Quotes");
// Add some data
$objPHPExcel->setActiveSheetIndex(0);
$loop = 0;
foreach($items as $value) {
$objPHPExcel->getActiveSheet()->SetCellValue('No', $loop);
$objPHPExcel->getActiveSheet()->SetCellValue('Item Name', $value);
$loop++;
}
// Redirect output to a client’s web browser (Excel5)
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="quotes.xls"');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
exit;
I've enabled errors and still blank page.
How do i solve? No file is downloading?
Well you should should be getting errors, or something written to your logs, because your code will throw a fatal
Fatal error: Uncaught exception 'PHPExcel_Exception' with message 'Invalid cell coordinate NO' in ...
Because NO is not a valid cell address in an Excel worksheet, nor is Item Name
The problem is these lines:
$objPHPExcel->getActiveSheet()->SetCellValue('No', $loop);
$objPHPExcel->getActiveSheet()->SetCellValue('Item Name', $value);
A valid cell address is a column (like A) combined with a row (like 1) to give a cell address of A1
Perhaps you meant something like:
$objPHPExcel->getActiveSheet()->SetCellValue('A'.($loop+1), 'No');
$objPHPExcel->getActiveSheet()->SetCellValue('B'.($loop+1), 'Item Name');
$objPHPExcel->getActiveSheet()->SetCellValue('C'.($loop+1), $loop);
$objPHPExcel->getActiveSheet()->SetCellValue('D'.($loop+1), $value);
I'm new in PHPExcel library and this is my first experience. I'm trying to export MySQL data to Ms Excel by formatting before. I've implemented a procedure that simply formats headings of the table with bold fonts and saves them with all relevants data to the spreadsheet. However, when I run the procedure, it displays the following error:
Fatal error: Call to undefined function getRow() in C:\Xampp\htdocs\test.php on line 182
Here is the PHP code:
require_once 'PHPExcel.php';
require_once 'PHPExcel/IOFactory.php';
require_once 'PHPExcel/Writer/Excel2007.php';
// create mysql query
$query_export = "SELECT * FROM `table1` ORDER BY `date` ASC";
// execute query
$result = mysqli_query($GLOBALS['mysqli'], $query_export) or die ("<b>Couldn't execute SQL query:</b> " . mysqli_error($GLOBALS['mysqli']));
try {
$sheet = new PHPExcel();
// set metadata
$sheet->getProperties()->setCreator('www.example.com')
->setLastModifiedBy('www.example.com')
->setTitle('Report on Table')
->setKeywords('report tables etc.');
// set default settings
$sheet->getDefaultStyle()->getAlignment()->setVertical(
PHPExcel_Style_Alignment::VERTICAL_TOP);
$sheet->getDefaultStyle()->getAlignment()->setHorizontal(
PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
$sheet->getDefaultStyle()->getFont()->setName('Calibri');
$sheet->getDefaultStyle()->getFont()->setSize(12);
// get reference to active spreadsheet in workbook
$sheet->setActiveSheetIndex(0);
$activeSheet = $sheet->getActiveSheet();
// populate with data
$row = getRow($result); // line 182
$colHeaders = array_keys($row);
$col = 'A';
$rownum = 1;
// set column headings
foreach ($colHeaders as $header) {
$activeSheet->setCellValue($col . $rownum, $header);
$activeSheet->getStyle($col . $rownum)->getFont()->setBold(true);
$activeSheet->getColumnDimension($col)->setAutoSize(true);
$col++;
}
// populate individual cells with data
do {
$col = 'A';
$rownum++;
foreach ($row as $value) {
$activeSheet->setCellValue($col++ . $rownum, $value);
}
} while ($row = getRow($result));
// setting headers
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment; filename=Export.xlsx');
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');
$writer = PHPExcel_IOFactory::createWriter($sheet, 'Excel2007');
$writer->save('php://output');
exit();
} catch (Exception $e) {
$error = $e->getMessage();
}
// display error
if (isset($error)) {
echo "<p>" .$error. "</p>";
}
// free resultset
mysqli_free_result($result);
// close db connection
$GLOBALS['mysqli']->close();
exit();
Any help is appreciated.
UPDATE
The following tutorial is used to create above mentioned code:
http://www.youtube.com/watch?v=L6MQQvBi-ks
I believe you need to define getRow or use something like this:
http://php.net/manual/en/mysqli-result.fetch-row.php
When i open the Excel file message appear:
the file you are trying to open, 'filename".xls', is in a different format than specified by the file extension. verify that the fileis not corrupted and is from a trusted source before opening the file."
The output is like this:
ÐÏࡱá;þÿ þÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ
>¶#d‹‹dggÿÿÿÿÿ .....
Here is my code..
<?php
require_once 'database.php';
include 'PHPExcel.php';
$phpExcel = new PHPExcel();
$phpExcel->getActiveSheet()->setTitle("My Sheet");
$phpExcel->setActiveSheetIndex(0)
->setCellValue('A1', 'Name.')
->setCellValue('B1', 'Age');
$qry_table = ("SELECT * FROM MEMBERS");
$inc=2;
while($data_array = mysql_fetch_array($qry_table))
{
$name = $data_array['Name'];
$age = $data_array['Age'];
$$phpExcel->setActiveSheetIndex(0)
->setCellValue('A'.$inc, $name)
->setCellValue('B'.$inc, $age);
$inc++;
}
$phpExcel->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($phpExcel, "Excel5");
$objWriter->save("php://output");
exit;
Where's your "mysql_query()" to query the database?
Change
$qry_table = ("SELECT * FROM MEMBERS");
to
$qry_table = mysql_query("SELECT * FROM MEMBERS");
//Edit:
And you've got a pointer ref. to an a variable which does not exsits
Change:
$$phpExcel->setActiveSheetIndex(0)
->setCellValue('A'.$inc, $name)
->setCellValue('B'.$inc, $age);
to:
$phpExcel->setActiveSheetIndex(0)
->setCellValue('A'.$inc, $name);
$phpExcel->setActiveSheetIndex(0)
->setCellValue('B'.$inc, $age);
When you get this error, we always recommend opening the file in a text editor and checking for leading or trailing white spaces (spaces, tabs, newlines), or a BOM marker, or any obvious PHP error messages in plain text in the file.
Try saving the file to your webserver, then opening it and see if the same error occurs
Greetings,
I am having trouble figuring out how to properly use PHP in general and PHPExcel in particular. I have read multiple posts on this topic and yet I've been running around in circles. Here is the relevant portion of my jacked up code:
$viewinv = mysql_connect($sqlsrv,$username,$password);
if (!$viewinv) { die('Could not connect to SQL server. Contact administrator.'); }
mysql_select_db($database, $viewinv) or die('Could not connect to database. Contact administrator.');
$query = "select unit_id,config,location from inventory;";
$result = mysql_query($query);
if ($result = mysql_query($query) or die(mysql_error())) {
$objPHPExcel = new PHPExcel();
$objPHPExcel->getActiveSheet()->setTitle('blah');
$rowNumber = 1;
$headings = array('Unit ID','Config','Location');
$objPHPExcel->getActiveSheet()->fromArray(array($headings),NULL,'A'.$rowNumber);
$rowNumber++;
while ($row = mysql_fetch_row($result)) {
$col = 'A';
foreach($row as $cell) {
$objPHPExcel->getActiveSheet()->setCellValue($col.$rowNumber,$cell);
$col++;
}
$rowNumber++;
}
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="myFile.xls"');
header('Cache-Control: max-age=0');
$objWriter->save('php://output');
exit();
}
echo 'a problem has occurred... no data retrieved from the database';
PHPExcel is definitely outputting data from the query, I can see bits and pieces of plaintext, but it is surrounded by a ton of random characters as if though I am looking at the contents of a compressed or compiled piece of data.
For example:
PKâh¿>G’D²Xð[Content_Types].xml”MNÃ0…÷œ"ò%nY „švAa •(0ö¤±êØ–gúw{&i‰#ÕnbEö{ßøyìÑdÛ¸l mð¥‘×ÁX¿(ÅÛü)¿’òF¹à¡;#1_滘±Øc)j¢x/%ê…Eˆày¦
Any pointers would be extremely appreciated
Your problem is certainly in outputting more content than just Excel data (which is contained in output buffer).
To solve your problem, just call
ob_clean(); //this will clean the output buffer
before sending header.
The problem will likely be resolved by matching the correct writer types to the correct content-types and file extension.
XLSX (office 2007+):
Writer : Excel2007 (PHPExcel_Writer_Excel2007)
Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
XLS (before office 2007):
Writer : Excel5 (PHPExcel_Writer_Excel5)
Content-Type: application/vnd.ms-excel
Using PHP, I'm trying to download a blob file that has already been uploaded to an Oracle 10g database. I've seen and imitated numerous examples I've found. When I access the page a File Download dialog appears allowing me to Open or Save. If I click Open, media player comes up as it should but never retrieves the file. If I choose Save, I always get an error message stating "Internet Explorer was not able to open this Internet site. The requested site is either unavailable or cannot be found. Please try again later."
Below is my code which is pretty straight forward and pretty much like the examples I've found.
<?php
header('Content-Disposition: attachment; filename='.$_GET['fileName']);
header('Content-length: '.$_GET['fileSize']);
header('Content-type: '.$_GET['mimeType']);
require_once("Include/Application.php");
$connection = oci_connect ($userID, $password, $TNS);
$phpCur = oci_new_cursor($connection);
$stmt = oci_parse($connection, "BEGIN MOR.DOWNLOAD_ATTACHMENT (:morID, :attachmentType, :phpCur); END;");
oci_bind_by_name($stmt, ":morID", $_GET['morID'], -1);
oci_bind_by_name($stmt, ":attachmentType", $_GET['attachmentType'], -1);
oci_bind_by_name($stmt, "phpCur", $phpCur, -1, OCI_B_CURSOR);
oci_execute($stmt);
oci_free_statement($stmt);
$output = '';
oci_execute($phpCur);
while( $row = oci_fetch_array($phpCur) )
$output .= $row['ATTACHMENT_BL'];
oci_free_statement($phpCur);
oci_close($connection);
echo $output;
exit;
?>
Use your db query and excecute first here is the data field is blob data:
$sql="SELECT FILE_NAME,data,length(data) as filesize FROM branch_data where id='$id'";
$r = $db->execute($sql);
$filename=$r->data[0]['FILE_NAME'];
$d=$r->data[0]['DATA'];
$filesize = $r->data[0]['FILESIZE'];
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.$filename.'"');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' .$filesize);
echo $d->load();
Add more error handling to your script. Any of the oci* function can fail and then subsequent steps will also fail. The documentation tells you what happens if a function fails and what the return value will be. E.g.
Return Values
Returns a connection identifier or FALSE on error.
If you set the Content-type header as late as possible, i.e. directly before the first output, you can send plain text or html that contains some sort of error message instead.
<?php
// error_reporting/ini_set: for testing purposes only.
error_reporting(E_ALL); ini_set('display_errors', 1);
require_once("Include/Application.php");
$connection = oci_connect ($userID, $password, $TNS);
if ( !$connection) {
die('database connection failed');
}
$phpCur = oci_new_cursor($connection);
if ( !$phpCur) {
die('creating cursor failed');
}
$stmt = oci_parse($connection, "BEGIN MOR.DOWNLOAD_ATTACHMENT (:morID, :attachmentType, :phpCur); END;");
if ( !$stmt) {
die('creating statement failed');
}
// and so on and on. Test the return values of each oci* function.
oci_close($connection);
header('Content-Disposition: attachment; filename='.$_GET['fileName']); // at least at basename() here
header('Content-length: '.$_GET['fileSize']); // strange...
header('Content-type: '.$_GET['mimeType']); // possible but still strange...
echo $output;
exit;