I want to display all the rows from a table with the corresponding column names above, which works. The problem is that it removes the first row from the results below the column names. It's as if the column row is somehow counted as a row in the while loop that displays the results, but I can't figure it out.
If I remove the column names code shown below all of the results are shown.
//COLUMN NAMES
foreach($headings as $heading) {
$objPHPExcel->getActiveSheet()->setCellValue($col.$rowNumber,$heading);
$col++;
}
All of the code shown below.
$query = "SELECT * FROM `" . $_SESSION['sess_table'] . "` ORDER by ID ASC";
if ($result = $mysqli->query($query)) {
$objPHPExcel = new PHPExcel();
$objPHPExcel->getActiveSheet()->setTitle($excelTitle);
$headingsrow = $result->fetch_assoc();
$headings = array_keys($headingsrow);
//COLUMN NAMES
$rowNumber = 1;
$col = 'A';
foreach($headings as $heading) {
$objPHPExcel->getActiveSheet()->setCellValue($col.$rowNumber,$heading);
$col++;
}
//RESULTS
$rowNumber = 3;
while ($row = $result->fetch_row()) {
$col = 'A';
foreach($row as $key => $cell) {
$objPHPExcel->getActiveSheet()->setCellValue($col.$rowNumber,$cell);
$col++;
}
$rowNumber++;
}
$objPHPExcel->getActiveSheet()->freezePane('A2');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="' . $excelFilename . '.xls"');
header('Cache-Control: max-age=0');
$objWriter->save('php://output');
exit();
}
In your code,
$rowNumber = 1;
$col = 'A';
foreach($headings as $heading) {
$objPHPExcel->getActiveSheet()->setCellValue($col.$rowNumber,$heading);
$col++;
}
you have increased the $col value instead of increasing $rowNumber value.
try this,
$rowNumber = 1;
$col = 'A';
foreach($headings as $heading) {
$objPHPExcel->getActiveSheet()->setCellValue($col.$rowNumber,$heading);
$rowNumber++;
}
You're fetching the first row to retrieve your headings, but then discarding it even though it contains data that you want to write as well
if ($result = $mysqli->query($query)) {
$objPHPExcel = new PHPExcel();
$objPHPExcel->getActiveSheet()->setTitle($excelTitle);
$row = $result->fetch_assoc();
$headings = array_keys($row);
//COLUMN NAMES
$rowNumber = 1;
$col = 'A';
foreach($headings as $heading) {
$objPHPExcel->getActiveSheet()->setCellValue($col.$rowNumber,$heading);
$col++;
}
//RESULTS
$rowNumber = 3;
do {
$col = 'A';
foreach($row as $key => $cell) {
$objPHPExcel->getActiveSheet()->setCellValue($col.$rowNumber,$cell);
$col++;
}
$rowNumber++;
} while ($row = $result->fetch_row());
}
Related
I have a excel file which contains certain rows with color i want to get the row id of a particular color code but unable to do it .. already searched but found nothing below is my code for PHPEXCEL
$cellColor = $objPHPExcel->getActiveSheet()->getStyle($cell->getCoordinate())->getFill()->getStartColor()->getRGB();
This will give me the color code and for the value i have $cell->getValue() where $cell is some variable for $cellIterator
foreach ($worksheet->getRowIterator() as $row) {
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(false);
foreach ($cellIterator as $cell)
{
$cellColor = $objPHPExcel->getActiveSheet()->getStyle($cell->getCoordinate())->getFill()->getStartColor()->getRGB();
if (!empty($cell->getCalculatedValue())) {
if ($cellColor == 'yellow') {
echo ($cellColor.'======'.$cell->getValue());
}
}
}
}
$cell->getValue() will give me the value of that particular color code But, the problem is if i have 2 rows with color yellow then $cell->getValue() will give two value like 0-> yellow1 1-> yellow2 but after deleting the 1st yellow colour data in excel then result will be 0-> yellow2 which is wrong what i need is 0->'' 1-> yellow2 Thats why i need row id for that particular color so that i can identify the row.
After hours of practicing got my expected result
$objPHPExcel = PHPExcel_IOFactory::load('someFile.xls');
foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
//$worksheetTitle = $worksheet->getTitle();
$highestRow = $worksheet->getHighestRow();
$highestColumn = $worksheet->getHighestColumn();
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
//$nrColumns = ord($highestColumn) - 64;
$groupCount = array();
$standardSetCount = array();
$standardCount = array();
$learningTargetCount = array();
for ($row = 1; $row <= $highestRow; ++$row) {
for ($col = 0; $col < $highestColumnIndex; ++$col) {
$cell = $worksheet->getCellByColumnAndRow($col, $row);
$colorCode = $objPHPExcel->getActiveSheet()->getStyle($cell->getCoordinate())->getFill()->getStartColor()->getRGB();
/*
* Yellow
*/
if ($colorCode == 'FFFF00') {
$val = $cell->getValue();
//$dataType = PHPExcel_Cell_DataType::dataTypeForValue($val);
$groupCount[] = $val; // $groupCount[] = $dataType;
}
/*
* gold
*/
if ($colorCode == 'CC9900') {
$val = $cell->getValue();
$standardSetCount[] = $val;
}
/*
* red
*/
if ($colorCode == 'FF3333') {
$val = $cell->getValue();
$standardCount[] = $val;
}
/*
* green
*/
if ($colorCode == '00CC33') {
$val = $cell->getValue();
$learningTargetCount[] = $val;
}
}
}
$group = (array_chunk($groupCount, $highestColumnIndex));
$standardSet = (array_chunk($standardSetCount, $highestColumnIndex));
$standard = (array_chunk($standardCount, $highestColumnIndex));
$learningTarget = (array_chunk($learningTargetCount, $highestColumnIndex));
echo '<pre>';
print_r($learningTarget);
}
I'm developing a small class that will allow you to pass queries and it will create a worksheet for each query.
FYI: This class is still in development and I will be reducing down into smaller functions.
My issue is that for some reason my sheet increment is off and I cant figure out where to put it.
I am calling my class like this:
$ex2 = new ExportToExcel2('Somefile');
$ex2->AddSheet('Sheet1', 'Select * from Division;');
$ex2->AddSheet('Sheet2', 'Select * from Zone');
$ex2->ExportMultiSheet();
I should have two tabs, "Sheet1" and "Sheet2". This is how my sheet ends up looking. All the data is on Sheet1 and Worksheet.
Here is my class:
class ExportToExcel2 {
public $AllSheetData = [];
protected $SheetData = [];
protected $PHPExcel = '';
protected $FileName = '';
function __construct($_filename) {
$this->FileName = $_filename;
$this->PHPExcel = new PHPExcel;
}
public function AddSheet($_WorkSheetName, $_Query) {
$this->SheetData['Sheet_Name'] = $_WorkSheetName;
$this->SheetData['Query'] = $_Query;
$this->AllSheetData[] = $this->SheetData;
unset($this->SheetData);
}
public function ExportMultiSheet() {
$Result='';
$count=0;
$this->PHPExcel->setActiveSheetIndex(0);
foreach($this->AllSheetData as $subarray)
{
foreach($subarray as $key => $value)
{
if($count>0)
{
$this->PHPExcel->createSheet($count);
$this->PHPExcel->setActiveSheetIndex($count);
}
if($key == 'Query') {
$Result = dbQuery($value);
//set header row
$row = 1; // 1-based index
$row_data = sqlsrv_fetch_array($Result, SQLSRV_FETCH_ASSOC);
$col = 0;
foreach(array_keys($row_data) as $key) {
$this->PHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $key);
$col++;
}
//set body rows
$row2 = 2;
while($row_data = sqlsrv_fetch_array($Result, SQLSRV_FETCH_ASSOC)) {
$col2 = 0;
foreach($row_data as $key=>$value) {
$this->PHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col2, $row2, $value);
$col2++;
}
$row2++;
}
$count++;
}
if($key =='Sheet_Name') {
$this->PHPExcel->getActiveSheet()->setTitle($value);
}
//set all columns to align left
$this->PHPExcel->getDefaultStyle()->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
//show gridlines?
$this->PHPExcel->getActiveSheet()->setShowGridlines(true);
//set columns a through z to auto width
for($col = 'A'; $col !== 'Z'; $col++) {
$this->PHPExcel->getActiveSheet()
->getColumnDimension($col)
->setAutoSize(true);
}
}
}
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="01simple.xls"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($this->PHPExcel, 'Excel2007');
$objWriter->save('php://output');
exit;
}
}
Any ideas on where to place my $count++?
Solved, Here is the finished class(until its not finished again)
class ExportToExcel2 {
public $AllSheetData = [];
protected $SheetData = [];
protected $PHPExcel = '';
protected $FileName = '';
function __construct($_filename) {
$this->FileName = $_filename;
$this->PHPExcel = new PHPExcel;
//clean the output buffer before download
ob_clean();
}
public function AddSheet($_WorkSheetName, $_Query) {
$this->SheetData['Sheet_Name'] = $_WorkSheetName;
$this->SheetData['Query'] = $_Query;
$this->AllSheetData[] = $this->SheetData;
unset($this->SheetData);
}
public function ExportMultiSheet($_ExportType='xls') {
if(!empty($this->AllSheetData)) {
$count=0;$Result='';
$this->PHPExcel->setActiveSheetIndex(0);
foreach($this->AllSheetData as $subarray) {
if($count>0){
$this->PHPExcel->createSheet(null);
$this->PHPExcel->setActiveSheetIndex($count);
}
$count++;
foreach($subarray as $key => $value) {
if($key == 'Query') {
$Result = dbQuery($value);
$this->SetHeaderCells($Result);
$this->SetbodyCells($Result);
}
if($key =='Sheet_Name') {
$this->PHPExcel->getActiveSheet()->setTitle($value);
}
}
}
$this->ExportType($_ExportType);
}
}
public function ExportSingleSheet($_Query, $_ExportType='xls') {
$Result = dbQuery($_Query);
$this->SetHeaderCells($Result);
$this->SetBodyCells($Result);
$this->SetProperties();
$this->ExportType($_ExportType);
}
private function ExportType($_ExportType) {
if($_ExportType=='xls') {
$this->DownloadXLS();
}
else if($_ExportType=='csv') {
$this->DownloadCSV();
}
}
private function SetProperties() {
//set all columns to align left
$this->PHPExcel->getDefaultStyle()->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
//show gridlines?
$this->PHPExcel->getActiveSheet()->setShowGridlines(true);
//set columns a through z to auto width
for($col = 'A'; $col !== 'Z'; $col++) {
$this->PHPExcel->getActiveSheet()
->getColumnDimension($col)
->setAutoSize(true);
}
//set the first sheet to open first
$this->PHPExcel->setActiveSheetIndex(0);
}
private function DownloadXLS() {
$this->SetProperties();
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="'.$this->FileName.'-'.date("y.m.d").'.xls"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($this->PHPExcel, 'Excel2007');
$objWriter->save('php://output');
exit;
}
private function DownloadCSV() {
$this->SetProperties();
header('Content-Type: text/csv');
header('Content-Disposition: attachment;filename="'.$this->FileName.'-'.date("y.m.d").'.csv"');
header('Cache-Control: max-age=0');
$objWriter = new PHPExcel_Writer_CSV($this->PHPExcel);
$objWriter->save("php://output");
exit;
}
private function SetHeaderCells($Result) {
$row = 1; // 1-based index
$row_data = sqlsrv_fetch_array($Result, SQLSRV_FETCH_ASSOC);
$col = 0;
foreach(array_keys($row_data) as $key) {
$this->PHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $key);
$col++;
}
}
private function SetBodyCells($Result) {
$row2 = 4;
while($row_data = sqlsrv_fetch_array($Result, SQLSRV_FETCH_ASSOC)) {
$col2 = 0;
foreach($row_data as $key=>$value) {
$this->PHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col2, $row2, $value);
$col2++;
}
$row2++;
}
}
}
You should first move the sheet generation code from the foreach($subarray loop to your foreach($this->AllSheetData (since you want to add new sheet for every.. well.. new sheet. Not for every new sheet property).
You should then use a very similar code to the one you had, and $counter will be used only within that part of the code. Note that to create a new sheet and place is as the last one, you should simply pass null to the createSheet() method.
So your code should look like this:
public function ExportMultiSheet() {
...
$count = 0;
foreach($this->AllSheetData as $subarray)
{
if ($count > 0)
{
$this->PHPExcel->createSheet(null);
$this->PHPExcel->setActiveSheetIndex($count);
}
$count++
foreach($subarray as $key => $value)
...
}
...
I have PHPExcel plugin to generated excel which data came from database, how if I wanted to add in additional text into a column A during the loop, and column B remain untouched data as from DB?
For example column A in DB is
alex
andy
jennifer
when output to excel, I wanted to add #domain.com for each name behind, wich will become
alex#domain.com
andy#domain.com
jennifer#domain.com
Code:
$query = "SELECT mail_name, account_id FROM email ORDER BY mail_name ASC";
$headings = array('Email', 'Id');
if ($result = mysql_query($query) or die(mysql_error())) {
// Create a new PHPExcel object
$objPHPExcel = new PHPExcel();
$objPHPExcel->getActiveSheet()->setTitle('emailList');
$rowNumber = 1;
$col = 'A';
foreach($headings as $heading) {
$objPHPExcel->getActiveSheet()->setCellValue($col.$rowNumber,$heading);
$col++;
}
// Loop through the result set
$rowNumber = 1;
while ($row = mysql_fetch_row($result)) {
$col = 'A';
foreach($row as $cell) {
$objPHPExcel->getActiveSheet()->setCellValue($col.$rowNumber,$cell);
$col++;
}
$rowNumber++;
}
Keep in mind that $col++ is not going to work.
What about this way?:
// Loop through the result set
$rowNumber = 1;
while ($row = mysql_fetch_row($result)) {
$objPHPExcel->getActiveSheet()
->setCellValue('A'.$rowNumber,$row['mail_name'].'#domain.com');
$objPHPExcel->getActiveSheet()
->setCellValue('B'.$rowNumber,$row['account_id']);
++$rowNumber;
}
This is my code,
Please tell me what am I missing?
// Field names in the first row
$sql1 = "SELECT `COLUMN_NAME`
FROM `INFORMATION_SCHEMA`.`COLUMNS`
WHERE `TABLE_SCHEMA`='test'
AND `TABLE_NAME`='user_tab'";
$res1 = mysql_query($sql1);
while ($row2 = mysql_fetch_assoc($res1)) {
$fields[] = $row2['COLUMN_NAME'];
}
//Data
$sql = "SELECT * FROM user_tab";
$res = mysql_query($sql);
echo date('H:i:s'), " Load from Excel5 template", EOL;
$objReader = PHPExcel_IOFactory::createReader('Excel5');
$objPHPExcel = $objReader->load("mytest.xls");
$logo = new PHPExcel_Worksheet_HeaderFooterDrawing();
$logo->setName('Logo');
$logo->setPath('image.jpg'); //Path is OK & tested under PHP
$logo->setHeight(38); //If image is larger/smaller than that, image will be proportionally resized
$objPHPExcel->getActiveSheet()->getHeaderFooter()->addImage($logo, PHPExcel_Worksheet_HeaderFooter::IMAGE_HEADER_LEFT);
echo date('H:i:s'), " Add new data to the template", EOL;
$col = 0;
foreach ($fields as $key => $value) {
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, 1, $value);
$col++;
}
$row = 2;
while ($row_data = mysql_fetch_assoc($res)) {
$col = 0;
foreach ($row_data as $key => $value) {
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $value);
$col++;
}
$row++;
}
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save(str_replace('.php', '.xls', __FILE__));
I am using this piece of code in PHP to query a database and import the data to an excel file. Currently I am getting the data from the database, but I can't get the headers.
Can anyone tell me how to get the headers from the database?
$objPHPExcel = new PHPExcel();
$col = 1;
while($row_data = mysql_fetch_assoc($result)) {
$row = 1;
foreach($row_data as $value) {
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $value);
$row++;
}
$col++;
}
$objPHPExcel = new PHPExcel();
$col = 1;
while($row_data = mysql_fetch_assoc($result)) {
$row = 1;
if ($col == 1) {
$row_headings = array_keys($row_data);
foreach($row_headings as $value) {
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $value);
$row++;
}
$row = 1;
$col++;
}
foreach($row_data as $value) {
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $value);
$row++;
}
$col++;
}