I want to export data to excel in CI. But i have issue
Undefined index: wc_order_id
If I
print_r(array_values($data)); exit;
the value is correct, only I cannot export to Excel.
This my controller:
public function createExcel($awals, $akhirs, $status) {
$fileName = 'Reservation.xlsx';
$data['data'] = $this->M_reservation->all_order($awals, $akhirs, $status) ;
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$total = 0;
$sheet->setCellValue('A1', 'No');
$sheet->setCellValue('B1', 'Booking ID');
$sheet->setCellValue('C1', 'Order Date');
$sheet->setCellValue('D1', 'Client Name');
$sheet->setCellValue('E1', 'Client Email');
$sheet->setCellValue('F1', 'Phone');
$sheet->setCellValue('G1', 'Inclution');
$sheet->setCellValue('H1', 'Room name');
$sheet->setCellValue('I1', 'Bed Order');
$sheet->setCellValue('J1', 'Status');
$sheet->setCellValue('K1', 'Total Order');
$rows = 2;
$no = 1;
$total=0;
foreach ($data as $val){
$sheet->setCellValue('A' . $rows, $no++);
$sheet->setCellValue('B' . $rows, $val['wc_order_id']);
$sheet->setCellValue('C' . $rows, $val['post_date']);
$sheet->setCellValue('D' . $rows, $val['display_name']);
$sheet->setCellValue('E' . $rows, $val['user_email']);
$sheet->setCellValue('F' . $rows, $val['meta_value']);
$sheet->setCellValue('G' . $rows, $val['display_name']);
$sheet->setCellValue('H' . $rows, $val['post_title']);
$sheet->setCellValue('I' . $rows, $val['room_num_search']);
$sheet->setCellValue('J' . $rows, $val['status']);
$sheet->setCellValue('K' . $rows, $val['total_order']);
$total = $total+$val['total_order'];
$rows++;
}
$sheet->setCellValue('B'.$rows , "Total");
$sheet->setCellValue('K'.$rows , $total);
$writer = new Xlsx($spreadsheet);
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="Reservation.xlsx"');
header('Cache-Control: max-age=0');
ob_clean();
$writer->save('php://output');
}
You're storing the value in $data['data'] which means the variable $data has a key named data that stores the resultant array. So, you can either
loop through $data['data']
$data['data'] = $this->M_reservation->all_order($awals, $akhirs, $status) ; // no change
// ...
// ...
foreach($data['data'] as $val){ // change here
// your code here
}
or store resultant array in $data
$data = $this->M_reservation->all_order($awals, $akhirs, $status) ; // change here
// ...
// ...
foreach($data as $val){ // no change
// your code here
}
See if it helps you.
Related
Hello i have an import of an xls file with multiple rows on it and i want to insert them into database only if the price columns has a value different than nothing else display an error msg. It works on half it only inserts those rows that have a value for price but instead returning the html error msg it returns the sql msg, that means it goes on the else branch.
Here is my code
$exceldata = array();
$uploadFilePath = 'uploads/'.basename($_FILES['doc']['name']);
move_uploaded_file($_FILES['doc']['tmp_name'], $uploadFilePath);
$inputfilename = 'uploads/'.$_FILES['doc']['name'].'';
// Read your Excel workbook
try
{
$inputfiletype = PHPExcel_IOFactory::identify($inputfilename);
$objReader = PHPExcel_IOFactory::createReader($inputfiletype);
$objPHPExcel = $objReader->load($inputfilename);
}
catch(Exception $e)
{
die('Error loading file "'.pathinfo($inputfilename,PATHINFO_BASENAME).'": '.$e->getMessage());
}
// Get worksheet dimensions
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();
$header=$_POST['membership'];
if($header==1)
{
// Loop through each row of the worksheet in turn
for ($row = 1; $row <= $highestRow; $row++)
{
// Read a row of data into an array
$rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row, NULL, TRUE, FALSE);
if ($rowData[0][9]=='')
{
echo 'No price for the product '.$rowData[0][1].'';
}
else
{
$a = array('8', '1', '2', '3', '4', '5','6');
$b = array($rowData[0][0], $rowData[0][2], $rowData[0][3],$rowData[0][5],$rowData[0][6],$rowData[0][8],$rowData[0][8]);
$c = array_combine($a, $b);
$slug = str_replace(" ", "-",$rowData[0][1]);
$slug = str_replace('"', "",$slug);
$slug = str_replace('/', "-",$slug);
$stmt=$dbh->prepare("INSERT INTO tbl_products (name,slug,description,price)
VALUES (:name,:slug,:desc,:pret)");
$stmt->bindParam(":name",$rowData[0][1]);
$stmt->bindParam(":slug",$slug);
$stmt->bindParam(":desc",$rowData[0][10]);
$stmt->bindParam(":pret",$rowData[0][9]);
$stmt->execute();
$id_product=$dbh->lastInsertId();
$stmt=$dbh->prepare("INSERT INTO tbl_products_images_gallery (id_product,name,image,sort_order)
VALUES (:id,:name,:image,100)");
$stmt->bindParam(":id",$id_product);
$stmt->bindParam(":name",$rowData[0][4]);
$stmt->bindParam(":image",$slug);
$stmt->execute();
$stmt=$dbh->prepare("SELECT id_category from tbl_catalog_categories where name=:name");
$stmt->bindParam(":name",$rowData[0][2]);
$stmt->execute();
if($row=$stmt->fetch())
{
$id_cat=$row['id_category'];
}
$stmt=$dbh->prepare("INSERT INTO tbl_products_to_categories (id_category,id_product)
VALUES (:id_cat,:id_prod)");
$stmt->bindParam(":id_cat",$id_cat);
$stmt->bindParam(":id_prod",$id_product);
$stmt->execute();
foreach($c as $key => $value)
{
$stmt=$dbh->prepare("INSERT INTO tbl_products_attributes_values (id_product,id_attribute,attribute_value)
VALUES (:id_product,:id_attribute,:value)");
$stmt->bindParam(":id_product",$id_product);
$stmt->bindParam(":id_attribute",$key);
$stmt->bindParam(":value",$value);
$stmt->execute();
}
}
}
}
if (empty($rowData[0][9])) perhaps?
Or test for null as well as for empty strings - nulls are perfectly valid response from PHPExcel...
especially as
$rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row, NULL, TRUE, FALSE);
with it's null second argument is telling PHPExcel to return a null value if the cell simply doesn't exist in the spreadsheet
Though you can change the rangeToArray() call to
$rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row, '', TRUE, FALSE);
to return an empty string instead of a null if the cell doesn't exist
I am exporting mysql data to an excel file using phpexcel library. The code works fine. But the excel file created doesn't have column name. I want to fetch them as well. Is there any built-in method for it? What adjustment do i need to make my code? Here is my current working code:
<?php
require_once 'PHPExcel/classes/PHPExcel.php';
$objPHPExcel = new PHPExcel();
$objPHPExcel->setActiveSheetIndex(0);
$rowcount = 1;
while($row = mysqli_fetch_array($rs))
{
$objPHPExcel->getActiveSheet()->SetCellValue('A'.$rowcount, $row['id']);
$objPHPExcel->getActiveSheet()->SetCellValue('B'.$rowcount, $row['title']);
$objPHPExcel->getActiveSheet()->SetCellValue('C'.$rowcount, $row['date']);
$rowcount++;
}
$filename = "backup-" . date("h.i.s.d-m-Y") . ".xls";
header('Content-Type: application/vnd.ms-excel');
header("Content-Disposition: attachment; filename=" . $filename);
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
?>
Use mysqli_fetch_fields for getting the field names.
I have edited your code and add column names in code. It might help you.
<?php
require_once 'PHPExcel/classes/PHPExcel.php';
$objPHPExcel = new PHPExcel();
$objPHPExcel->setActiveSheetIndex(0);
$rowcount = 1;
$fieldinfo=mysqli_fetch_fields($rs);
foreach ($fieldinfo as $val)
{
$objPHPExcel->getActiveSheet()->SetCellValue('A'.$rowcount, $val->id);
$objPHPExcel->getActiveSheet()->SetCellValue('B'.$rowcount, $val->title);
$objPHPExcel->getActiveSheet()->SetCellValue('C'.$rowcount, $val->date);
}
$rowcount = 2;
while($row = mysqli_fetch_array($rs))
{
$objPHPExcel->getActiveSheet()->SetCellValue('A'.$rowcount, $row['id']);
$objPHPExcel->getActiveSheet()->SetCellValue('B'.$rowcount, $row['title']);
$objPHPExcel->getActiveSheet()->SetCellValue('C'.$rowcount, $row['date']);
$rowcount++;
}
$filename = "backup-" . date("h.i.s.d-m-Y") . ".xls";
header('Content-Type: application/vnd.ms-excel');
header("Content-Disposition: attachment; filename=" . $filename);
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
?>
If i am right , you were searching for something like below
Insert Title Row
$f=0;
$fChar='A';
while($f<mysql_num_fields($rs)){
$objPHPExcel->getActiveSheet()->setCellValue($fChar.'1', mysql_fetch_field($rs,$f++)->name);
$objPHPExcel->getActiveSheet()->getStyle($fChar.'1')->applyFromArray(
array(
'fill' => array(
'type' => PHPExcel_Style_Fill::FILL_SOLID,
'color' => array('rgb'=>'E1E0F7'),
),
'font' => array(
'bold' => true,
)
)
);
$fChar++;
}
Now insert values
$fC=2;
while($row=mysql_fetch_array($rs,MYSQL_BOTH)){
$fChar='A';
$f=0;
while($f<mysql_num_fields($rs)){
$objPHPExcel->getActiveSheet()->setCellValue($fChar++.''.$fC, $row[$f++]);
}
$fC++;
}
You need to change the code something like below to show the column name and data
//this is for showing the column name
$q = mysql_query("SHOW COLUMNS FROM table_name");
if (mysql_num_rows($q) > 0) {
while ($row_q = mysql_fetch_assoc($q)) {
$col='A';
$objPHPExcel->getActiveSheet()->SetCellValue($col.$rowcount, $row_q['Field']);
$col++;
}
$rowcount++;
}
//this is for showing coulmn data based in results
while($row_data1 = mysql_fetch_assoc($rs)){
$col=0;
foreach($row_data1 as $key=>$value){
$objPHPExcel->getActiveSheet()->SetCellValueByColumnAndRow($col, $rowcount, $value);
$col++;
}
$rowcount++;
}
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');
}
}
This is the PHP code, I don't know much about PHPExcel to make it run faster, ideally I don't want to limit to 10000 rows (still takes at least 5 minutes before it sends the excel file)
Any ideas?
The script basically selects all data from the sqlite database then it loops the keys of the first row to add as titles for the columns.
Then it loops all rows and sets each cell value.
After this it adds the formula columns.
Then sends the excel data to the user.
The script is run at: http://example-site.org/getStatsExcel.php - so each time a user goes to that page, it runs this script - I think I should store the database per day and if it's already stored for that day, then just return the file, else generate the excel again...
<?php
date_default_timezone_set('Europe/Zurich');
require_once 'phpexcel/Classes/PHPExcel.php';
ini_set('max_execution_time', 900);
$dbname = 'admin';
$fullPath = sprintf('/var/www/fullpathtosqlite/%s.sqlite', $dbname);
$dbh = new PDO('sqlite:' . $fullPath);
$phpExcel = new PHPExcel();
$phpExcel->getProperties()->setTitle('Export : Statistics');
$phpExcel->getProperties()->setCreator('PHPExcel Stats Script');
$sheet = $phpExcel->getActiveSheet();
$sheet->setTitle('stats');
$phpExcel->setActiveSheetIndex(0);
$sql = 'SELECT * FROM (SELECT * FROM statistics ORDER BY timestamp DESC LIMIT 10000) ORDER BY timestamp ASC';
if(!$stmt = $dbh->prepare($sql, array(PDO::ATTR_CURSOR, PDO::CURSOR_SCROLL))) {
die(var_export($dbh->errorinfo(), TRUE));
}
$stmt->execute();
// Fetch the first row
$row = $stmt->fetch(PDO::FETCH_ASSOC, PDO::FETCH_ORI_NEXT);
$results = array();
// Iterate over the results and print each one in a line
while ($row != false) {
$results[] = $row;
// Fetch the next line
$row = $stmt->fetch(PDO::FETCH_ASSOC, PDO::FETCH_ORI_NEXT);
}
$row = 1;
$col = 0;
foreach ($results[0] as $key => $value) {
$sheet->setCellValueByColumnAndRow($col, $row, $key);
$col++;
}
// date
$sheet->setCellValueByColumnAndRow($col, $row, 'date');
$col++;
// time
$sheet->setCellValueByColumnAndRow($col, $row, 'time');
$col++;
// full_date
$sheet->setCellValueByColumnAndRow($col, $row, 'full_date');
$row = 2;
foreach ($results as $result) {
$col = 0;
foreach ($result as $key => $value) {
$sheet->setCellValueByColumnAndRow($col, $row, $value);
$col++;
}
// date
$sheet->setCellValueByColumnAndRow($col, $row, '=DATE(LEFT(A' . $row . ',4),MID(A' . $row . ',5,2),MID(A' . $row . ',7,2))');
$col++;
// time
$sheet->setCellValueByColumnAndRow($col, $row, '=TIME(MID(A' . $row . ',9,2),MID(A' . $row . ',11,2),MID(A' . $row . ',13,2))');
$col++;
// full_date
$sheet->setCellValueByColumnAndRow($col, $row, '=F' . $row . '+G' . $row);
$row++;
}
$sheet->getStyle('F2:F' . $row)
->getNumberFormat()
->setFormatCode('dd/mm/yyyy');
$sheet->getStyle('G2:G' . $row)
->getNumberFormat()
->setFormatCode('h:mm AM/PM');
$sheet->getStyle('H2:H' . $row)
->getNumberFormat()
->setFormatCode('dd/mm/yyyy hh:mm');
foreach(range('A','H') as $columnID) {
$sheet->getColumnDimension($columnID)->setAutoSize(true);
}
header("Content-Type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=\"statistics.xls\"");
header("Cache-Control: max-age=0");
$objWriter = PHPExcel_IOFactory::createWriter($phpExcel, "Excel5");
$objWriter->save("php://output");
exit;
The more data you're working with, the longer it will take. That's why we recommend that generating large spreadsheets should be farmed off to a back-end process so that it doesn't leave the user waiting while it builds the spreadsheet.
If you can build these large data spreadsheets "offline", then do so; if you can cache them, then do so.
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');