Excel Upload giving me blank sheet - php

I am uploading data from my database into excel using PHPExcel. The download occurs correctly only that it is returning an empty excel sheet for me and i dont seem to get what the problem really is. I would be glad if you could help me out. Find below my code snippet for the upload.
<?php
include("connection/db.php");
$uploadedStatus = 0;
$msg="";
include 'Classes/PHPExcel/IOFactory.php';
if(isset($_POST['submit'])){
$schId=$_POST['schId'];
$program=$_POST['program'];
$objPHPExcel = new PHPExcel();
if($program=="All"){
echo $query1 = "SELECT * FROM studentrec WHERE schId='$schId'";
}
else{
$query1 = "SELECT * FROM studentrec WHERE schId='$schId' AND program='$program'";
}
$exec1 = mysqli_query($conn,$query1) or die ("Error in Query1".mysqli_error());
$serialnumber=0;
//Set header with temp array
$tmparray =array("Student ID","First Name","Last Name");
//take new main array and set header array in it.
$sheet =array($tmparray);
while ($res1 = mysqli_fetch_array($exec1))
{
$tmparray =array();
$serialnumber = $serialnumber + 1;
array_push($tmparray,$serialnumber);
$employeelogin = $res1['stdId'];
array_push($tmparray,$employeelogin);
$employeename = $res1['fst_name'];
array_push($tmparray,$employeename);
$lst_name = $res1['lst_name'];
array_push($tmparray,$lst_name);
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__));
}
?>

Related

I want to enter information in the order of user ID in Excel

I want to enter information in the order of user ID in Excel.
For example, if a user ID has 3 orders, I need to enter her 3 orders first and then the next customers in the same order.
just like db:
But the code output:
The correct output is line 11 onwards
$users = "837|3710|4543";
$connect->set_charset("utf8");
require('Classes/PHPExcel.php');
$phpExcel = new PHPExcel;
$inputFileType = PHPExcel_IOFactory::identify("hadi111.xlsx");
$phpExcel = PHPExcel_IOFactory::createReader("$inputFileType");
$phpExcel = $phpExcel->load('hadi111.xlsx');
$writer = PHPExcel_IOFactory::createWriter($phpExcel, "Excel2007");
$sheet = $phpExcel ->getActiveSheet();
$start = 2;
$ex = explode("|",$users);
foreach($ex as $usercode){
if(!is_file("chek/$usercode")){
if(!is_file("chek/$usercode")){
$get = mysqli_query($connect, "select * from exel where id = '$usercode'");
while($row = $get->fetch_assoc()){
$res[] = $row;
}
echo json_encode($res);
foreach($res as $record){
$sheet ->getCell("C$start")->setValue($record['melli']);
$sheet ->getCell("E$start")->setValue($record['name']);
$sheet ->getCell("Q$start")->setValue($record['price']);
$sheet ->getCell("P$start")->setValue($record['count']);
$sheet ->getCell("O$start")->setValue($record['code']);
$sheet ->getCell("J$start")->setValue($record['status']);
$sheet ->getCell("G$start")->setValue($record['postal']);
$sheet ->getCell("A$start")->setValue($record['date']);
$sheet->getColumnDimension('A')->setAutoSize(true);
$sheet->getColumnDimension('C')->setAutoSize(true);
$sheet->getColumnDimension('E')->setAutoSize(true);
$sheet->getColumnDimension('Q')->setAutoSize(true);
$sheet->getColumnDimension('P')->setAutoSize(true);
$sheet->getColumnDimension('O')->setAutoSize(true);
$sheet->getColumnDimension('J')->setAutoSize(true);
$sheet->getColumnDimension('G')->setAutoSize(true);
$start++;
}
touch("chek/$usercode");
}
}else{
$start++;
}
}
$writer->save('hadi2w.xlsx');

Remove empty First rows in PHPexcel

I'm Uploading the excel file to the database on the website using phpexcel.
But first row is being skiped and entered my data.
The results is shown in the picture below.
i need a help..
How can I solve?
I have the following code.
<?
include_once('./_common.php'); //database option
include 'Classes/PHPExcel.php';
include 'Classes/PHPExcel/IOFactory.php'; //load phpexcel
$up_file = "aaa.xlsx";
try {
$objReader = PHPExcel_IOFactory::createReaderForFile($up_file);
//set the read only
$objReader->setReadDataOnly(true);
//read a excel file
$objExcel = $objReader->load($up_file);
// select first cell
$objExcel->setActiveSheetIndex(0);
$objWorksheet = $objExcel->getActiveSheet();
$rowIterator = $objWorksheet->getRowIterator();
foreach ($rowIterator as $row) {
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(false);
}
$maxRow = $objWorksheet->getHighestRow();
$maxCell = $objWorksheet->getHighestColumn();
for ($i = 0 ; $i <= $maxRow; $i++) {
$acell = $objWorksheet->getCell('A' . $i)->getValue(); // A
$bcell = $objWorksheet->getCell('B' . $i)->getValue(); // B
$acell = addslashes($acell);
$bcell = addslashes($bcell);
//$sql = "insert into echo_test (a,b,c,d,e) values ('$a','$b','$c','$d','$e')";
$sql = "insert into echo_excel set
bcat = '$acell',
scat = '$bcell',
";
sql_query($sql);
}
echo $maxRow . " Data inserting finished !";
} catch (exception $e) {
echo 'error!';
}
?>
Simply test the $bcat variable to see if it is empty before trying to insert data into your table.
$acell = $objWorksheet->getCell('A' . $i)->getValue(); // A
$bcell = $objWorksheet->getCell('B' . $i)->getValue(); // B
if (empty($bcell)) {continue;} // no value for bcat so go to the next row
$acell = addslashes($acell);
$bcell = addslashes($bcell);

export mysql data from two tables to excel using php and phpexcel

I am trying to get data from to mysql table and output to a single excel file. The data needs to come side-by-side.
But the output excel file contains only special characters instead of mysql data. Please point me to the right direction.
Here is my code:
<?php
// connection with the database
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "redhat";
$dbname = "was";
mysql_connect($dbhost,$dbuser,$dbpass);
mysql_select_db($dbname);
// require the PHPExcel file
require 'phpexcel/Classes/PHPExcel.php';
//$q2 = "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = ".$dbname."";
$sql = "SHOW TABLES"; $res = mysql_query($sql); $num_tables = mysql_num_rows($res);
$table = $num_tables;
$i = 1;
echo $i;
echo $table;
// write all table names with a variable value like table1 table2 table3
// simple query
while($i <= $table){
//$query = "SELECT servicedate,recdate,dostoreclag,casesrec,scandate,casesentered,casespending,casecountdiff,entrydate,rcvdtolag FROM hos1report ORDER by id DESC";
$query = "SELECT servicedate,recdate,dostoreclag,casesrec,scandate,casesentered,casespending,casecountdiff,entrydate,rcvdtolag FROM hos".$i."report";
$headings = array('Service Date','Rec. Date','DOS to Rec. Lag','Cases Rec.','scan Date','Cases Entered','Cases Pending','Cases Count Diff','Entry Date','Rec. to Entry Lag');
if ($result = mysql_query($query) or die(mysql_error())) {
// Create a new PHPExcel object
$objPHPExcel = new PHPExcel();
$objPHPExcel->getActiveSheet()->setTitle('Report');
$rowNumber = 8;
if ($i == 1) {
$col = 'A';
} elseif ($i == 2) {
$col = 'L';
}
// $col = 'A';
foreach($headings as $heading) {
$objPHPExcel->getActiveSheet()->setCellValue($col.$rowNumber,$heading);
$col++;
}
// Loop through the result set
$rowNumber = 9;
while ($row = mysql_fetch_row($result)) {
if ($i == 1) {
$col = 'A';
} elseif ($i == 2) {
$col = 'L';
}
// $col = 'A';
// $col = 'A';
foreach($row as $cell) {
$objPHPExcel->getActiveSheet()->setCellValue($col.$rowNumber,$cell);
$col++;
}
$rowNumber++;
}
// Freeze pane so that the heading line won't scroll
$objPHPExcel->getActiveSheet()->freezePane('A2');
// Save as an Excel BIFF (xls) file
$i++;
}
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="report.xls"');
header('Cache-Control: max-age=0');
}
$objWriter->save('php://output');
exit();
echo 'a problem has occurred... no data retrieved from the database';
?>
Try this code :
<?php
// connection with the database
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "redhat";
$dbname = "was";
mysql_connect($dbhost,$dbuser,$dbpass);
mysql_select_db($dbname);
// require the PHPExcel file
require 'phpexcel/Classes/PHPExcel.php';
//$q2 = "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = ".$dbname."";
$sql = "SHOW TABLES"; $res = mysql_query($sql); $num_tables = mysql_num_rows($res);
$table = $num_tables;
$i = 1;
echo $i;
echo $table;
// write all table names with a variable value like table1 table2 table3
// simple query
while($i <= $table){
//$query = "SELECT servicedate,recdate,dostoreclag,casesrec,scandate,casesentered,casespending,casecountdiff,entrydate,rcvdtolag FROM hos1report ORDER by id DESC";
$query = "SELECT servicedate,recdate,dostoreclag,casesrec,scandate,casesentered,casespending,casecountdiff,entrydate,rcvdtolag FROM hos".$i."report";
$headings = array('Service Date','Rec. Date','DOS to Rec. Lag','Cases Rec.','scan Date','Cases Entered','Cases Pending','Cases Count Diff','Entry Date','Rec. to Entry Lag');
if ($result = mysql_query($query) or die(mysql_error())) {
// Create a new PHPExcel object
$objPHPExcel = new PHPExcel();
$objPHPExcel->getActiveSheet()->setTitle('Report');
$rowNumber = 8;
if ($i == 1) {
$col = 'A';
} elseif ($i == 2) {
$col = 'L';
}
// $col = 'A';
foreach($headings as $heading) {
$objPHPExcel->getActiveSheet()->setCellValue($col.$rowNumber,$heading);
$col++;
}
// Loop through the result set
$rowNumber = 9;
while ($row = mysql_fetch_row($result)) {
if ($i == 1) {
$col = 'A';
} elseif ($i == 2) {
$col = 'L';
}
// $col = 'A';
// $col = 'A';
foreach($row as $cell) {
$objPHPExcel->getActiveSheet()->setCellValue($col.$rowNumber,$cell);
$col++;
}
$rowNumber++;
}
// Freeze pane so that the heading line won't scroll
$objPHPExcel->getActiveSheet()->freezePane('A2');
// Save as an Excel BIFF (xls) file
$i++;
}
// $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
// header('Content-Type: application/vnd.ms-excel');
// header('Content-Disposition: attachment;filename="report.xls"');
// header('Cache-Control: max-age=0');
}
// 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');
// $objWriter->save('php://output');
exit();
echo 'a problem has occurred... no data retrieved from the database';
?>
Hope it run well... :)

Export csv file to download from mysql with PHP

I am trying to get csv file from my mysql db and sent it to the browser for download.
I read some posts about it but I cant get the file downloaded.
When I run my code the file is not downloaded.
I send POST through ajax to this file.
Here is my Code :
<?php
download_send_headers();
$mysqli = new mysqli(*****);
$mysqli->set_charset("utf8");
$sql = "SELECT trainer, COUNT(trainer) FROM personal_traning WHERE gym = ? GROUP BY trainer";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('s', $_POST['gym']);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($trainer, $trainerCount);
$f = fopen('php://output', 'w');
$results = array();
$row = array();
$row[0] = "Trainer name";
$row[1] = "Count";
fputcsv($f, $row);
while ($stmt->fetch())
{
$row = array();
$row[0] = $trainer;
$row[1] = $trainerCount;
fputcsv($f, $row);
}
$output = stream_get_contents($f);
fclose($f);
echo $output;
die();
function download_send_headers() {
header('Content-Disposition: attachement;filename="name";');
header('Content-Type: application/csv; charset=UTF-8');
}
?>
How can i do this ?
Try to add .csv to the filename of the header.

PHPExcel - How to export results from multiple queries

Is there a way to export results from multiple queries to single excel sheet using PHPExcel? Here's what I have so far and it works with one query:
<?php
// connection with the database
$dbhost = "localhost";
$dbuser = "admin";
$dbpass = "password";
$dbname = "databasename";
mysql_connect($dbhost,$dbuser,$dbpass);
mysql_select_db($dbname);
// require the PHPExcel file
require 'classes/PHPExcel.php';
// simple query
$query = "SELECT denisCheckedby, denisStatus, denisDate, denisNotes FROM tblDenis ORDER by denisID DESC";
$headings = array('Checked By', 'Successfull?','Date','Notes');
if ($result = mysql_query($query) or die(mysql_error())) {
// Create a new PHPExcel object
$objPHPExcel = new PHPExcel();
$objPHPExcel->getActiveSheet()->setTitle('Backup Check');
$rowNumber = 1;
$col = 'A';
foreach($headings as $heading) {
$objPHPExcel->getActiveSheet()->setCellValue($col.$rowNumber,$heading);
$col++;
}
// Loop through the result set
$rowNumber = 2;
while ($row = mysql_fetch_row($result)) {
$col = 'A';
foreach($row as $cell) {
$objPHPExcel->getActiveSheet()->setCellValue($col.$rowNumber,$cell);
$col++;
}
$rowNumber++;
}
// Freeze pane so that the heading line will not scroll
$objPHPExcel->getActiveSheet()->freezePane('A2');
$objPHPExcel->getActiveSheet()->getStyle('A1:D1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
// Set column widths
$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setAutoSize(true);
$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setAutoSize(true);
$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setAutoSize(true);
// Set fonts
$objPHPExcel->getActiveSheet()->getStyle('A1:D1')->getFont()->setBold(true);
// Save as an Excel BIFF (xls) file
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="Backup Check.xls"');
header('Cache-Control: max-age=0');
$objWriter->save('php://output');
exit();
}
echo 'a problem has occurred... no data retrieved from the database';
?>
How do I do the same using multiple queries? For example, my 2nd query would be:
"SELECT curtisCheckedby, curtisStatus, curtisDate, curtisNotes FROM tblCurtis ORDER by curtisID DESC";
Thank you very much for any help.

Categories