How to fetch column names with mysql data using phpexcel? - php

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

Related

Undefined index: wc_order_id

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.

PHPExcel fatal error GarbageCollect()

Good day, i'm trying to export data from my table to excel with PHPExcel 1.8. Here is my script so far :
$this->load->library('excels');
$objPHPExcel = new PHPExcel();
$objPHPExcel->getProperties()->setTitle("export")->setDescription("none");
$objPHPExcel->setActiveSheetIndex(0);
$query = $this->db->query("SELECT * FROM RESIGN");
$fields = $query->list_fields();
$col = 0;
foreach ($fields as $field)
{
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, 1, $field);
$col++;
}
$row = 2;
foreach($query->result() as $data)
{
$col = 0;
foreach ($fields as $field)
{
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $data->$field);
$col++;
}
$row++;
}
$objPHPExcel->setActiveSheetIndex(0);
$objWriter = PHPExcel_IOFactory::createWriter($this->excel, 'Excel5');
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="Products_'.date('dMy').'.xls"');
header('Cache-Control: max-age=0');
$objWriter->save('php://output');
when i run that function. Excel file will be downloaded , inside the excel file i receive this error.
<b>Fatal error</b>: Call to a member function garbageCollect() on null in <b>D:\xampp\htdocs\payroll\application\third_party\PHPExcel\Writer\Excel5.php</b> on line <b>115</b><br />

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

How to remove the top two empty rows in the excel sheet?

Below the sample codes. It's may help you..
When i'm change the row number(1) into 5 then seven rows are empty in excel sheet.(LOCATION : setCellValueByColumnAndRow($col, 1, $field);)
$objPHPExcel = new PHPExcel();
$objPHPExcel->getProperties()->setTitle("export")->setDescription("none");
$objPHPExcel->setActiveSheetIndex(0);
$fields = array('ram','one','two');
$col = 0;
foreach ($fields as $field)
{
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, 1, $field);
$col++;
}
header('Content-Type: text/csv');
header('Content-Disposition: attachment;filename="Export.csv"');
header('Cache-Control: max-age=0');
$objWriter->save('php://output');
$objPHPExcel = new PHPExcel();
$objPHPExcel->getProperties()->setTitle("export")->setDescription("none");
$objPHPExcel->setActiveSheetIndex(0);
$field = array('ram','one','two');
$col = 0;
foreach ($fields as $field)
{
if(empty($field)){
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, 1, $field);
$col++;
}
}
header('Content-Type: text/csv');
header('Content-Disposition: attachment;filename="Export.csv"');
header('Cache-Control: max-age=0');
$objWriter->save('php://output');
You're defining $field but foreach references $fields.... that s makes a lot of difference
$field = array('ram','one','two');
and
foreach ($fields as $field)
Try defining your array with the correct variable name
$fields = array('ram','one','two');

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