PHPExcel : Image is not inserting in excel file - php

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

Related

Populating a mysql database with an excel file using phpspreadsheet

I am trying to populate a mysql database with an excel file using phpspreadsheet library. I am doing it in the following way but I get just the first row. How can I do it for all the rows
$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($target_file);
$worksheet = $spreadsheet->getActiveSheet();
$rows = [];
$outer = 1;
foreach ($worksheet->getRowIterator() AS $row) {
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(FALSE); // This loops through all cells,
$cells = [];
foreach ($cellIterator as $cell) {
$cells[] = $cell->getValue();
}
$rows[] = $cells;
while($outer > 1){
$data = [
'testTaker' => $cells[1],
'correctAnswers' => $cells[2],
'incorrectAnswers' => $cells[3],
];
if($this->testModel->addTest($data)){
die('it worked');
} else {
die('Something went wrong');
}
}
$outer++;
}
This is how I am importing a XLSX spreadsheet with phpSpreadSheet into a MySQL database using PDO (modified to fit your criteria).
// read excel spreadsheet
$reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
if($reader) {
$reader->setReadDataOnly(true);
$spreadsheet = $reader->load($target_file);
$sheetData = $spreadsheet->getActiveSheet()->toArray();
foreach($sheetData as $row) {
// get columns
$testTaker = isset($row[0]) ? $row[0] : "";
$correctAnswers = isset($row[1]) ? $row[1] : "";
$incorrectAnswers = isset($row[2]) ? $row[2] : "";
// insert item
$query = "INSERT INTO item(testTaker, correctAnswers, incorrectAnswers) ";
$query .= "values(?, ?, ?)";
$prep = $dbh->prepare($query);
$prep->execute(array($testTaker, $correctAnswers, $incorrectAnswers));
}
}

Get a template and dont overwrite the cells into blank spaces

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

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

How to include the graph inside the codeigniter export excel

I have the userlist with comment count.I have export excel using below libaraies and codes.
How to include graph inside the excel sheet.
Here is my output:
E.g.:
Sno USER CommentCount
1 User1 10
2 User2 12
3 User3 21
How to form graph or chart inside the excel using codeigniter.
Library function:
class Export{
function to_excel($array, $filename) {
header('Content-type: application/vnd.ms-excel');
header('Content-Disposition: attachment; filename='.$filename.'.xls');
$h = array();
foreach($array as $row){
foreach($row as $key=>$val){
if(!in_array($key, $h)){
$h[] = $key;
}
}
}
echo '<table><tr>';
foreach($h as $key) {
$key = ucwords($key);
echo '<th>'.$key.'</th>';
}
echo '</tr>';
foreach($array as $row){
echo '<tr>';
foreach($row as $val)
$this->writeRow($val);
}
echo '</tr>';
echo '</table>';
}
function writeRow($val) {
echo '<td>'.utf8_decode($val).'</td>';
}
}
Controller code:
public function userlist(){
$sql = $this->export_model->user_export();
$this->export->to_excel($sql, 'UserList');
}
finally I got it using PHP EXCEL . Code is below
include "Classes/PHPExcel.php";
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="graphdemo.xlsx"');
header('Cache-Control: max-age=0');
$workbook = new PHPExcel();
$objRichText = new PHPExcel_RichText();
$objBold = $objRichText->createTextRun('Name');
$objBold->getFont()->setBold(true);
$workbook->getActiveSheet()->getCell('A1')->setValue($objRichText);
$objRichText = new PHPExcel_RichText();
$objBold = $objRichText->createTextRun('Sharing Count');
$objBold->getFont()->setBold(true);
$workbook->getActiveSheet()->getCell('B1')->setValue($objRichText);
$workbook->setActiveSheetIndex(0);
$sheet = $workbook->getActiveSheet();
$sheet->getPageMargins()->setTop(0.6);
$sheet->getPageMargins()->setBottom(0.6);
$sheet->getPageMargins()->setHeader(0.4);
$sheet->getPageMargins()->setFooter(0.4);
$sheet->getPageMargins()->setLeft(0.4);
$sheet->getPageMargins()->setRight(0.4);
$workbook->getProperties()->setTitle("Demo");
$workbook->getProperties()->setCreator("Demo");
$workbook->getProperties()->setLastModifiedBy("Demo");
$workbook->getProperties()->setCompany("Demo");
$Requete = "SELECT COUNT(*) As cnt , name FROM `users` GROUP BY user_id ";
$result = mysql_query($Requete);
while ($row = mysql_fetch_array($result)){
$bname[] = $row["name"];
$bk_co[] = $row["cnt"];
}
$data =$bname;
$row = 2;
foreach($data as $point) {
$sheet->setCellValueByColumnAndRow(0, $row++, $point);
}
$data = $bk_co;
$row = 2;
foreach($data as $point) {
$sheet->setCellValueByColumnAndRow(1, $row++, $point);
}
$values = new PHPExcel_Chart_DataSeriesValues('Number', 'Worksheet!$B$1:$B$10');
$categories = new PHPExcel_Chart_DataSeriesValues('String', 'Worksheet!$A$1:$A$10');
$series = new PHPExcel_Chart_DataSeries(
PHPExcel_Chart_DataSeries::TYPE_BARCHART,
PHPExcel_Chart_DataSeries::GROUPING_CLUSTERED,
array(0),
array(),
array($categories),
array($values)
);
$series->setPlotDirection(PHPExcel_Chart_DataSeries::DIRECTION_COL);
$layout = new PHPExcel_Chart_Layout();
$plotarea = new PHPExcel_Chart_PlotArea($layout, array($series));
$chart = new PHPExcel_Chart('sample', null, null, $plotarea);
$chart->setTopLeftPosition('F2');
$chart->setBottomRightPosition('N25');
$sheet->addChart($chart);
$writer = PHPExcel_IOFactory::createWriter($workbook, 'Excel2007');
$writer->setIncludeCharts(TRUE);
$writer->save('php://output');

Getting the headers in PHPExcel

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

Categories