PHPExcel additional text add to column - php

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;
}

Related

Import Excel Data to mysql 1 sheet only using PHP

I am trying to import a grade sheet into mysql database but that excel file have multiple sheet how can i make it so only a specified sheet will be going into my database
$uploadfile=$_FILES['uploadfile']['tmp_name'];
require 'PHPExcel/Classes/PHPExcel.php';
require_once 'PHPExcel/Classes/PHPExcel/IOFactory.php';
$objExcel =PHPExcel_IOFactory::load($uploadfile);
foreach($objExcel->getWorksheetIterator() as $worksheet)
{
$highestrow=$worksheet->getHighestRow();
for($row=8;$row<=$highestrow;$row++){
$name=$worksheet->getCellByColumnAndRow(1,$row)->getValue();
$finalgrade=$worksheet->getCellByColumnAndRow(15,$row)->getValue();
if($finalgrade != ''){
$insertqry = "INSERT INTO `user`(`stud_name`, `final_grade`) VALUES ('$name',' $finalgrade')";
$insertres = mysqli_query($con,$insertqry);
}
}
}
As far as I understand you are looking to get data from a specific sheet.
In PHPExcel there is this function: setActiveSheetIndex(sheet_index)
You can try like this:
$uploadfile = 'test.xlsx';
$objExcel = PHPExcel_IOFactory::load($uploadfile);
$objData = PHPExcel_IOFactory::createReader('Excel2007');
//read only
$objData->setReadDataOnly(true);
$objPHPExcel = $objData->load($uploadfile);
// Select sheet to get
$sheet = $objPHPExcel->setActiveSheetIndex(1);
$Totalrow = $sheet->getHighestRow();
$LastColumn = $sheet->getHighestColumn();
$TotalCol = PHPExcel_Cell::columnIndexFromString($LastColumn);
$data = [];
// Proceed to loop through each data cell
// Repeat rows, Since the first row is assumed to be the column header, we will loop the value from line 2
for ($i = 2; $i <= $Totalrow; $i++) {
//---- Loop column
for ($j = 0; $j < $TotalCol; $j++) {
// Proceed to get the value of each cell into the array
$data[$i - 2][$j] = $sheet->getCellByColumnAndRow($j, $i)->getValue();;
}
}
var_dump($data);
i just deleted the foreach and add getSheetName()
require 'PHPExcel/Classes/PHPExcel.php';
require_once 'PHPExcel/Classes/PHPExcel/IOFactory.php';
$objExcel =PHPExcel_IOFactory::load($uploadfile);
$worksheet = $objExcel->getSheetByName('GEN.AVERAGE');
$highestrow=$worksheet->getHighestRow();
for($row=8;$row<=$highestrow;$row++){
$name=$worksheet->getCellByColumnAndRow(1,$row)->getValue();
$finalgrade=$worksheet->getCellByColumnAndRow(15,$row)->getValue();
if($finalgrade != ''){
$insertqry = "INSERT INTO `user`(`stud_name`, `final_grade`) VALUES ('$name',' $finalgrade')";
$insertres = mysqli_query($con,$insertqry);
}
}

How to get row id using color code in phpexcel

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);
}

PHPExcel - Avoid storing empty cells in database after import

I'm fairly new to PHPExcel and was wondering if you would be able to assist me with the code below.
Exporting with PHPExcel works perfectly, but when I am importing a xls or xlsx document, it stores the content of the sheet (which is what i want) but also inserts almost 200 blank entries into the Database, from a sheet with 4 rows of data.
I've searched the internet for quite a while now, but cannot seem to find the solution to this.
See my code below:
$storedir = "../uploads/". $_FILES['file']['name'];
$store = move_uploaded_file($_FILES['file']['tmp_name'], $storedir);
$filename = $_FILES['file']['name'];
$srow = $_POST['srow'];
if ($store) {
$objPHPExcel = PHPExcel_IOFactory::load($storedir);
foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
$highestRow = $worksheet->getHighestRow();
$highestColumn = $worksheet->getHighestColumn();
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
$nrColumns = ord($highestColumn) - 64;
for ($row = $srow; $row <= $highestRow-2; ++ $row) {
$val=array();
for ($col = 1; $col < $highestColumnIndex; ++ $col) {
$cell = $worksheet->getCellByColumnAndRow($col, $row);
$val[] = $cell->getValue();
}
$savetodb = mysql_query("INSERT INTO `students` (`gender`, `name`, `surname`) VALUES ('".$val[1]."','".$val[2]."','".$val[3]."')") or die (mysql_error());
}
}
}
I've not added my Connection codes and includes for PHPExcel classes and IOFactories, although they are in the code.
Any assistance would be greatly appreciated.

PHPExcel multiple foreach loops

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());
}

PHPexcel: Combine two variables into one cell

I'm trying to create an excel sheet with data from a mysql database.
At some point I want to combine two variables into one cell.
EXAMPLE:
$customer = $row["city"].' '.$row["name"]; // Doesn't work
$rowNumber = 2;
while ($row = mysql_fetch_assoc($result)) {
$col = 'A';
$sheet->setCellValueExplicit('A'.$rowNumber, $row['routenr']);
$sheet->setCellValueExplicit('C'.$rowNumber, $date);
$sheet->setCellValueExplicit('D'.$rowNumber, $customer);
$rowNumber++;
}
Any ideas?
Try This.
$rowNumber = 2;
while ($row = mysql_fetch_assoc($result)) {
$customer = $row["city"].' '.$row["name"];
$col = 'A';
$sheet->setCellValueExplicit('A'.$rowNumber, $row['routenr']);
$sheet->setCellValueExplicit('C'.$rowNumber, $date);
$sheet->setCellValueExplicit('D'.$rowNumber, $customer);
$rowNumber++;
}
Your example won't work because you're concatenating $row["city"] and $row["name"] before you've retrieved $row from the database result set. Nothing to do with PHPExcel, just basic PHP.
Move your concatenation inside the while loop so that $row["city"] and $row["name"] will be populated with actual values from the retrieved row
$rowNumber = 2;
while ($row = mysql_fetch_assoc($result)) {
$customer = $row["city"].' '.$row["name"];
$sheet->setCellValueExplicit('A'.$rowNumber, $row['routenr']);
$sheet->setCellValueExplicit('C'.$rowNumber, $date);
$sheet->setCellValueExplicit('D'.$rowNumber, $customer);
$rowNumber++;
}

Categories