Get a template and dont overwrite the cells into blank spaces - php

I'm having a situation, that i get one template in excel, where i just want to add the information of my database, but when i do that put the template blank just with the information. Please tell me what i'm doing wrong. I'm new to PHPExcel
MODEL:
public function export_excel($id)
{
require_once APPPATH.'Classes/PHPExcel.php';
$queryResult = $this->get($id);
$objPHPExcel = new PHPExcel();
$objPHPExcel->setActiveSheetIndex(0);
$result = mysql_query($queryResult[0]['query_sql']) or die (mysql_error());
//echo "SQL = ", $queryResult[0]['query_sql']; // pass query allright
// Initialise the Excel row number
$rowCount = $queryResult[0]['start_line'];
//start of printing column names as names of MySQL fields
$column = $queryResult[0]['title_cell'];
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 = $rowCount+1;
while($row = mysql_fetch_row($result))
{
$column = 'B';
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()->getColumnDimension($column)->setAutoSize(true);
$objPHPExcel->getActiveSheet()->setCellValue($column.$rowCount, $value);
$column++;
}
$rowCount++;
}
$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
//$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
// Write the Excel file to filename some_excel_file.xlsx in the current directory
if($queryResult[0]['template_location'] !=null){
$objWriter->save($queryResult[0]['template_location']);
//echo date('H:i:s') , " Write to Excel2007 format" , EOL;
return 1;
}
else{
$objWriter->save('php://output');
//echo date('H:i:s') , " Write to Excel2007 format" , EOL;
return 1;
}
return null;
}

You're not reading the template, you need to read first from the template and write into:
something like this:
$objReader = PHPExcel_IOFactory::createReader('Excel5');
$objPHPExcel = $objReader->load($queryResult[0]['template_location']);
i hope it helped

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

phpexcel to html only a portion

I'm working on phpexcel. The File I'm working on is from tally export file. I have to read this file and save the data to each user .
For example from this file I need only A2:G10 as HTML/TABLE. So i can display to the particular member (Adv. Chandra Mogan) individually.
I NEED A TABLE FOR ONLY A PORTION OF THE SHEET
What I have done so far:
protected function doExcelUpdate() {
$inputFileName = $this->getParameter('temp_directory') . '/file.xls';
if (!file_exists($inputFileName)) {
$this->addFlash('sonata_flash_error', 'File: not found in temp directory');
return;
}
$this->addFlash('sonata_flash_info', 'File: exist');
try {
$inputFileType = PHPExcel_IOFactory::identify($inputFileName);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader->load($inputFileName);
} catch (Exception $e) {
$this->addFlash('sonata_flash_error', 'Error in PHPExcel');
return;
}
$sheet = $objPHPExcel->getSheet(0);
if (!$sheet) {
$this->addFlash('sonata_flash_error', 'Error in reading sheet');
return;
}
$objPHPExcel->getSheet(0)
->getStyle('A1:G10')
->getProtection()
->setLocked(
PHPExcel_Style_Protection::PROTECTION_PROTECTED
);
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'HTML');
$objWriter->setSheetIndex(0);
$objWriter->save($this->getParameter('temp_directory') . '/output.html');
}
A1:G10 is not locked. Entire sheet is printed.
First point: "Locking" doesn't change the sheet size, or set a "view window"; it protects parts of the sheet from being edited.
Second point: "Locking" is a feature of Excel, and supported for excel writers, but not for HTML.
Third point: there is no direct mechanism to write only part of a worksheet.
As a suggestion, you might create a new blank worksheet, and then copy the data/style information from the cell range that you want in your your main worksheet to that new worksheet starting from cell A1; then send that worksheet to the HTML Writer.
You can't achive this using locked or hidden cells when you use HTML writer.
You can use a workaround creating a new worksheet and after adding the portion you want to display.
For mantain style on new worksheet (like font, color, border) you must extract it for each cell from the orginal worksheet and apply to the copied cells.
The same thing is for merged cells in the old worksheet.
Your function doExcelUpdate() should be like this:
protected function doExcelUpdate()
{
$inputFileName = $this->getParameter('temp_directory').'/file.xls';
if (!file_exists($inputFileName)) {
$this->addFlash('sonata_flash_error', 'File: not found in temp directory');
return;
}
$this->addFlash('sonata_flash_info', 'File: exist');
try {
$inputFileType = PHPExcel_IOFactory::identify($inputFileName);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$originalPHPExcel = $objReader->load($inputFileName);
} catch (Exception $e) {
$this->addFlash('sonata_flash_error', 'Error in PHPExcel');
return;
}
$originalSheet = $originalPHPExcel->getSheet(0);
if (!$sheet) {
$this->addFlash('sonata_flash_error', 'Error in reading sheet');
return;
}
// Get the data of portion you want to output
$data = $originalSheet->rangeToArray('A1:G11');
$newPHPExcel = new PHPExcel;
$newPHPExcel->setActiveSheetIndex(0);
$newSheet = $newPHPExcel->getActiveSheet();
$newSheet->fromArray($data);
// Duplicate style for each cell from original sheet to the new sheet
for ($i = 1; $i < 11; $i++) {
for ($j = 0; $j <= 6; $j++) {
$style = $originalSheet->getStyleByColumnAndRow($j, $i);
$newSheet->duplicateStyle($style, PHPExcel_Cell::stringFromColumnIndex($j).(string)$i);
}
}
// Merge the same cells that are merged in the original sheet
foreach ($originalSheet->getMergeCells() as $cells) {
$inRange = false;
foreach (explode(':', $cells) as $cell) {
$inRange = $originalSheet->getCell($cell)->isInRange('A1:G11');
}
// Merge only if in range of the portion of file you want to output
if ($inRange) {
$newSheet->mergeCells($cells);
}
}
$objWriter = PHPExcel_IOFactory::createWriter($newPHPExcel, 'HTML');
$objWriter->save($this->getParameter('temp_directory').'/output.html');
}
UP TO NOW FOR THE WORK TO BE COMPLETED, I HAVE DONE THIS,
private function doExcelUpdate() {
$inputFileName = $this->getParameter('temp_directory') . '/file.xls';
$synopsis = PHPExcel_IOFactory::load($inputFileName)->getSheet(0);
$column = $synopsis->getHighestColumn();
$row = $synopsis->getHighestRow();
$this->cleanUserPayment();
$this->doExcelUpdateTable($synopsis, $column, $row);
$this->deleteExcelFile();
}
private function cleanUserPayment() {
$em = $this->getDoctrine()->getManager();
$classMetaData = $em->getClassMetadata('AppBundle\Entity\UserPayment');
$connection = $em->getConnection();
$dbPlatform = $connection->getDatabasePlatform();
$connection->beginTransaction();
try {
$connection->query('SET FOREIGN_KEY_CHECKS=0');
$q = $dbPlatform->getTruncateTableSql($classMetaData->getTableName());
$connection->executeUpdate($q);
$connection->query('SET FOREIGN_KEY_CHECKS=1');
$connection->commit();
} catch (\Exception $e) {
$connection->rollback();
}
}
private function doExcelUpdateTable($synopsis, $column, $row) {
set_time_limit(300);
$t = [];
for ($r = 1; $r <= $row; $r++) {
for ($c = "A"; $c <= $column; $c++) {
$cell = $synopsis->getCell($c . $r)->getFormattedValue();
if ($cell == 'Ledger:') {
$t[] = $r;
}
}
}
$t[] = $row+1;
$numItems = count($t);
$i = 0;
$em = $this->getDoctrine()->getManager();
foreach ($t as $key => $value) {
if (++$i != $numItems) {
$up = new UserPayment();
$up->setName($synopsis->getCell('B' . $value)->getFormattedValue());
$up->setMessage($this->doExcelUpdateTableCreate($synopsis, $column, $value, $t[$key + 1]));
$em->persist($up);
// $this->addFlash('sonata_flash_error', 'Output: ' . $synopsis->getCell('B' . $value)->getFormattedValue() . $this->doExcelUpdateTableCreate($synopsis, $column, $value, $t[$key + 1]));
}
}
$em->flush();
$this->addFlash('sonata_flash_success', "Successfully updated user bills. Total data updated::" . count($t));
}
private function doExcelUpdateTableCreate($synopsis, $column, $rowS, $rowE) {
$mr = NULL;
$x = 0;
$alphas = range('A', $column);
$oneTable = '<table border="1">';
for ($r = $rowS; $r < $rowE; $r++) {
$oneTable .= "<tr>";
for ($c = "A"; $c <= $column; $c++) {
if ($x > 0) {
$x--;
continue;
}
$mr = NULL;
$x = 0;
$cell = $synopsis->getCell($c . $r);
$cellVal = $cell->getFormattedValue();
if ($cellVal == NULL) {
$cellVal = " ";
}
$cellRange = $cell->getMergeRange();
if ($cellRange) {
$mr = substr($cellRange, strpos($cellRange, ":") + 1, 1);
$upto = array_search($mr, $alphas);
$x = ($upto - array_search($c, $alphas));
$oneTable .= "<td colspan=" . ($x + 1) . " style='text-align:right;'>" . $cellVal . "</td>";
} else {
$oneTable .= "<td>" . $cellVal . "</td>";
}
}
$oneTable .= "</tr>";
}
$oneTable .= "</table>";
return $oneTable;
}
private function deleteExcelFile() {
$filesystem = new \Symfony\Component\Filesystem\Filesystem();
$filesystem->remove($this->getParameter('temp_directory') . '/file.xls');
}

Excel functions showing as it is when converting excel to CSV in php

We are converting excel to CSV with every sheet. For example if a excel file has 5 sheets then we are converting 5 CSV file for every sheet.
Its working fine except one thing.
As we know excel sheet has some formulas for calculation like sum, Average etc..., So when we are converting them to CSV file, Then function is showing as it is, Their calculated value is not showing, which we can read as a excel sheet.
This is the function which we are using
function write_csv($filename,$definename){
$dir = "";
$file_arr = array();
array_push($file_arr, $filename);
// Make CSV File
$list = array();
foreach($file_arr as $val)
{
$arr_data = array();
// echo $val;
$objPHPExcel = PHPExcel_IOFactory::load($dir . $val);
// print_r($objPHPExcel->getSheetNames());exit;
$loadedSheetNames = $objPHPExcel->getSheetNames();
foreach($loadedSheetNames as $sheetIndex => $loadedSheetName) {
// echo $sheetIndex;
$objPHPExcel->setActiveSheetIndex($sheetIndex);
$fp = fopen($definename.'_'.$sheetIndex.'.csv', 'a');
$cell_collection = $objPHPExcel->getActiveSheet()->getCellCollection();
// print_r($cell_collection);
foreach($cell_collection as $cell)
{
$column = $objPHPExcel->getActiveSheet()->getCell($cell)->getColumn();
$row = $objPHPExcel->getActiveSheet()->getCell($cell)->getRow();
$data_value = $objPHPExcel->getActiveSheet()->getCell($cell)->getValue();
//header will / should be in row 1 only. of course this can be modified to suit your need.
// Skip Rows From Top if you have header in Excel then Change 0 to 1
if($row == 0)
{
$header[$row][$column] = $data_value;
}
else
{
$arr_data[$row]['row'] = $row;
$arr_data[$row][$column] = $data_value;
}
}
$data = $arr_data;
foreach($data as $val1)
{
$num_col = sizeof($val1) - 1; // get number of columns in Excel
break;
}
$lwrcol=array();
foreach($data as $val2)
{
$alphaArr = range('A','Z');
$colArr = range('A',$alphaArr[$num_col - 1]);
foreach($colArr as $col)
{
$lwrcol[$col] = isset($val2[$col]) ? utf8_decode($val2[$col]) : "";
fwrite($fp,$lwrcol[$col].",");
}
fwrite($fp,"\n");
}
// chmod(getcwd()."/file.csv", 0777);
fclose($fp);
}
}
}
Please tell me what we are doing wrong.
Complete Code:
http://pastebin.com/DaRBSpqP

PhpExcel export data from a website to CSV file

I want to export data from orangehrm attendance report to csv file by using phpexcel but I don't know how to do it:
$records = array();
foreach ($empRecords as $employee) {
$hasRecords = false;
$attendanceRecords = $employee->getAttendanceRecord();
$total = 0;
foreach ($attendanceRecords as $attendance) {
$from = $this->date . " " . "00:" . "00:" . "00";
$end = $this->date2 . " " . "23:" . "59:" . "59";
if (strtotime($attendance->getPunchInUserTime()) >= strtotime($from) && strtotime($attendance->getPunchInUserTime()) <= strtotime($end)) {
if ($attendance->getPunchOutUtcTime()) {
$total = $total + round((strtotime($attendance->getPunchOutUtcTime()) - strtotime($attendance->getPunchInUtcTime())) / 3600, 2);
}
$records[] = $attendance;
$hasRecords = true;
}
}
if ($hasRecords) {
$last = end($records);
$last->setTotal($total);
} else {
$attendance = new AttendanceRecord();
$attendance->setEmployee($employee);
$attendance->setTotal('---');
$records[] = $attendance;
}
}
// Algorithm to export filtered/ searched data
if($post['export'] == '1'){
//require_once 'PHPExcel/Reader/Excel15.php';
//require_once 'PHPExcel/Reader/Excel2007.php';
require_once 'PHPExcel/IOFactory.php';
require_once 'PHPExcel.php';
$objPHPExcel = new PHPExcel();
$objActSheet = $objPHPExcel->getActiveSheet();
$objActSheet->setTitle('Staff AttendanceRecord');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('Attendance.xslx');
}
csvYou didn't mention the structure of your array ($records)..
Hope it's like
$records[] = array('EMPLOYEE'=>'name1','TOTAL'=>'total1'),array('EMPLOYEE'=>'name2','TOTAL'=>'total2');
Please try code below
if($post['export'] == '1')
{
if(!empty($records))
{
require_once 'PHPExcel/IOFactory.php';
require_once 'PHPExcel.php';
$objPHPExcel = new PHPExcel(); // Create new PHPExcel object
$column = A;
$headings=array('EMPLOYEE','TOTAL');
for($c=0;$c<count($headings);$c++)
{
$objPHPExcel->getActiveSheet()->setCellValue($column.'1',$headings[$c]); // Add column heading data
if($c==count($headings)-1)
{
break;// Need to terminate the loop when coumn letter reachs max
}
$column++;
}
while (list($key,$value) = each($records))
{
$objPHPExcel->getActiveSheet()->setCellValue('A'.$j,$value['EMPLOYEE']);
$objPHPExcel->getActiveSheet()->setCellValue('B'.$j,$value['TOTAL']);
$j++;
}
$objActSheet->setTitle('Staff AttendanceRecord');
$workbookName = 'Attendance';
// Redirect output to a client’s web browser (Excel5)
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="'.$workbookName.'.csv"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
}
}

PHP simple Excel lib

I'm looking for a way to do the following:
$file = 'file.xls';
$input = '<tr><td>Some input</td></tr>';
if (!file_exists($file))
{
create_excel($file); //Create the sheet
input_titles($file); //Add column titles
}
else
{
add_input_to_the_last_line($input);
}
Is there a library which can simply do the above?
You could use PHPExcel library:
Example Usage:
$objPHPExcel = new PHPExcel();
$objPHPExcel->setActiveSheetIndex(0);
$rowCount = 1;
while($row = mysql_fetch_array($result)){
$objPHPExcel->getActiveSheet()->SetCellValue('A'.$rowCount, <your_row_name>);
$objPHPExcel->getActiveSheet()->SetCellValue('B'.$rowCount, <your_row_name>);
$rowCount++;
}
$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
$objWriter->save('your_file_name.xlsx');

Categories