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');
}
Related
PHP Script written for SuiteCRM improting is supposed to loop through all files in the directory and import each to Database. Having a lot of trouble.
Script reads and works on the first file only then finishes when it should loop :(
Importing works fine and data is added the the database from first file.
function MemberImportJob()
{
try
{
$config = new Configurator();
$config->loadConfig();
$xmlDataDir = 'custom/wimporter/eidimport';
$directoryContent = scandir($xmlDataDir);
//foreach ($directoryContent as $itemFile)
foreach (glob($xmlDataDir) as $itemfile)
{
var_dump($itemfile);
if (is_dir($xmlDataDir . DIRECTORY_SEPARATOR . $itemFile)) continue;
if (strcasecmp(substr($itemFile, -4), ".csv") != 0) continue;
$oFile = fopen($xmlDataDir . DIRECTORY_SEPARATOR . $itemFile, 'r');
if ($oFile !== FALSE)
{
$header = NULL;
$data = Array();
while (($data[] = fgetcsv($oFile, 90000, ',')) !== FALSE) { }
fclose($oFile);
//combine into a nice associative array:
$arow=Array();
$fields = array_shift($data);
foreach ($data as $i=>$arow)
{
array_combine " . $i);
if (is_array($arow)) {
$data[$i] = array_combine($fields, $arow);}
}
unset($arow);
$num = count($data);
for ($row=0; $row < $num - 1; $row++)
{
$Member = BeanFactory::getBean("locte_Membership");
$Member=$Member->retrieve_by_string_fields(array('last_name' => $data[$row]["LAST NAME"], 'first_name' => $data[$row]["FIRST NAME"], 'lcl_affiliate_number' => $data[$row]["AFFILIATE"]));
$MemberID = $Member->id;
if (is_null($Member)) {
$Member = BeanFactory::newBean('locte_Membership');
$delta = fillPerson($data[$row], $Member, "FULL NAME");
if(count($delta))
{
$Member_id = $Member->save();
}
} else {
v
var_dump($Member->id);
$delta = fillFoundrecord($data[$row], $Member, "FULL NAME");
echo("record Updated!");
$Member_id = $Member->save();
}
unset($data[$row]);
}
}
return true;
}
} catch (Exception $e)
{
return false;
}
}
If I have 14000 records then there is memory space issue coming and if records are 1000 I am able to upload but takes 00:30 mints .
Can anyone help me to optimize this code that I can upload records in minimum time?
Here is my code:
<?php
namespace ProjectName\AdminBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RedirectResponse;
class TakeoverController extends Controller {
public function uploadtakeoverAction(Request $request) {
ini_set('max_execution_time', 0); //0=NOLIMIT
ini_set('memory_limit', '8192M');
//start - code to check ip address
$checkipaddress = $this->get('userlogin')->CheckIPAddress();
if (empty($checkipaddress)) {
return $this->redirect($this->generateUrl('admin'));
}
//end - code to check ip address
$em = $this->getDoctrine()->getManager();
$helper = $this->get('common_helper_function');
$reqImage = $_FILES;
$validExtensions = array('xls', 'xlsx');
if (isset($_FILES) && !empty($_FILES)) {
$ext = pathinfo($_FILES['file']["name"], PATHINFO_EXTENSION);
if (!in_array($ext, $validExtensions)) {
echo "1";
die;
}
}
$admin = $this->get('security.context')->getToken()->getUser();
$takeoverfile = $this->uploadtakeoverFile($reqImage);
$takeovertm = array();
$insertedrecord = array();
$existingrecord = array();
$importmulitpletakeover = array();
$atmservicesamount = array();
$errormessage = '';
$neeerro = '';
if ($takeoverfile) {
$phpExcelObject = $this->get('phpexcel')->createPHPExcelObject();
$file = $takeoverfile;
if (!file_exists($file)) {
exit("Please run 05featuredemo.php first.");
}
$objPHPExcel = \PHPExcel_IOFactory::load($file);
foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
$i = 0;
foreach ($worksheet->getRowIterator() as $row) {
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(false); // Loop all cells, even if it is not set
$totalindex = $row->getRowIndex();
// echo $row->getRowIndex();
if ($row->getRowIndex() != 1) { // first index is title index so not cosider
foreach ($cellIterator as $cell) {
if (!is_null($cell)) {
//the below columns are from A to AF
if ($cell->getColumn() == 'A') {
$val1= trim($cell->getValue());
}
if ($cell->getColumn() == 'B') {
$val2= $cell->getValue();
}
if ($cell->getColumn() == 'C') {
$val3= trim($cell->getValue());
}
if ($cell->getColumn() == 'D') {
$val3.=', ' . trim($cell->getValue());
}
if ($cell->getColumn() == 'E') {
$val3.=', ' . trim($cell->getValue());
}
}
// insert this fields into database from here of column A to AF
}
unlink($takeoverfile);
$response = new Response(json_encode($importmulitpletakeover));
return $response;
} else {
$message = 'Image has not been uploaded ';
echo "2";
die;
}
}
}}}
protected function uploadtakeoverFile($uploadedReceipt) {
//start - code to check ip address
$checkipaddress = $this->get('userlogin')->CheckIPAddress();
if (empty($checkipaddress)) {
return $this->redirect($this->generateUrl('admin'));
}
//end - code to check ip address
$basicPath = $_SERVER['DOCUMENT_ROOT'] . '/ProjectName/web/uploads';
$basicReceiptPath = $basicPath . '/FolderName';
if (null === $uploadedReceipt) {
return;
} else {
$extention = explode('.', #$uploadedReceipt['file']["name"]);
$filename = #$extention[0] . '_' . time() . '.' . #$extention[1];
$this->path = $basicReceiptPath . '/' . #$filename;
if (move_uploaded_file($uploadedReceipt['file']["tmp_name"], $this->path))
return $this->path;
else
return false;
}
}
}
The most effective style will be to only use Doctrine DBAL and write SQL code.
Documentation states that Doctrine ORM is not fit for mass inserts.
There are "hacks" like disabling SQLLogger and batch processing, but using only DBAL will save you more time.
I want to import data using php mysql from excel sheet containing 1.6 million records. What is the best way to do this?
this is the sample code I have used to iterate excel file and insert data in database:
public function iterateData($file_name) {
$fileDirectory = '';
$file_name = $fileDirectory . $file_name;
if (file_exists($file_name)) {
$this->truncateTable();
include 'PHPExcel2/Classes/PHPExcel/IOFactory.php';
$objReader = PHPExcel_IOFactory::createReader('Excel2007');
$objPHPExcel = $objReader->load($file_name);
$count = 1;
foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
foreach ($worksheet->getRowIterator() as $row) {
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(true); // Loop all cells, even if it is not set
$cellValues = array();
foreach ($cellIterator as $cell) {
if (!is_null($cell)) {
$cellValues[] = $cell->getCalculatedValue();
}
}
if (isset($cellValues[0]) && $cellValues[0] != 'Product' && $cellValues[0] != '') {
$this->inserInDatabase($cellValues);
} elseif (empty($cellValues[0]) && empty($cellValues[1]) && empty($cellValues[2])) {
continue;
}
}
if ($objPHPExcel->getSheetCount() == $count) {
return TRUE;
}
$count++;
}
} else {
return FALSE;
}
} private function inserInDatabase($data) {
$dbDetails = array(
'db_name' => '*',
'db_pass' => '*',
'db_host' => 'localhost',
'db_user' => '*'
);
$dbh = dbConnect::connect($dbDetails);
$date = date('Y-m-d H:i:s');
$sql = "INSERT INTO product_description (product_id, prpoduct_description, price, created_date) values ('" . mysql_escape_string($data[0]) . "', '" . mysql_escape_string($data[1]) . "', '" . mysql_escape_string($data[2]) . "', '$date')";
if (!$dbh->dbh->query($sql)) {
die('Database Connection Failed.');
}
}
export you excel data to csv format, and then import the csv format to mysql
you can import using ;
if($request->hasFile('excelFile')){
$inputFileType = 'Xlsx';
$inputFileName = $request->file('excelFile')->getRealPath();
/** Create a new Reader of the type defined in $inputFileType **/
$reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
/** Advise the Reader that we only want to load cell data **/
$reader->setReadDataOnly(true);
/** Load $inputFileName to a Spreadsheet Object **/
$spreadsheet = $reader->load($inputFileName);
foreach ($spreadsheet->getActiveSheet()->toArray() as $key => $row) {
$data['question'] = $row[0];
$data['option1'] = $row[1];
$data['option2'] = $row[2];
$data['option3'] = $row[3];
$data['option4'] = $row[4];
$data['correct'] = $row[5];
$data['status'] = 1;
$data['receiver'] = 'all';
$data['createdOn'] = date("Y-m-d H:i:s");
if(!empty($data)) {
DB::table('questions')->insert($data);
}
}
}
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'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