When Trying to export multi dimensional array into excel using php I got only empty excel file , i am new to work with phpExcel
I know that this kind of questions were already asked and answered but I am tired by analyse all the answers ,
I need to know what is the problem in my code, how will clear it to get expected output.
I need output as in the Image
<?php
ini_set('display_errors', 1);
require_once('/var/www/html/aws/arun/PHPExcel/Classes/PHPExcel.php');
$sheet = array();
$array1 = array("Body","ID","Group");
array_push($sheet,$array1);
$array2 = array("Mesaage 1" , "10", "11");
array_push($sheet,$array2);
echo '<pre>';
print_r($sheet);
echo '</pre>';
$objPHPExcel = new PHPExcel();
$objPHPExcel->getActiveSheet()->setTitle('Excel Export');
foreach($sheet as $row => $val){
foreach($val as $column => $value){
$objPHPExcel->setActiveSheetIndex(0)->setCellValueByColumnAndRow($column, $row, $value);
}
}
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="test.xls"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');
?>
Using the code below you can export the file to a csv if that works for you?
$sheet = array();
$array1 = array("Body","ID","Group");
array_push($sheet,$array1);
$array2 = array("Mesaage 1" , "10", "11");
array_push($sheet,$array2);
echo '<pre>';
print_r($sheet);
echo '</pre>';
//open file ready to write to
//'c+' opens the file or creates if it doesn't already exist
$fo = fopen('YOURFILEPATHHERE','c+');
//loop through array
foreach ($sheet as $lines) {
//push array values to line in the csv file
fputcsv($fo,$lines);
}
//close file
fclose($fo);
This outputs a csv that meets your requirements.
Make sure you have permission to write into the location you specify at YOURFILEPATHHERE.
Find out more information about fputcsv and fopen visit http://php.net/manual/en/function.fputcsv.php and http://php.net/manual/en/function.fopen.php respectively.
$row needs to start from 1 if you're using setCellValueByColumnAndRow(), because MS Excel worksheet rows start from 1 (note that Excel never has cell A0)
But you might find using the Worksheet's fromArray() method is easier
Try this code and change little bit according to your requirement
$header = array("Body","ID","Group");
$array2 = array("Mesaage 1" , "10", "11");
$list = array ($header);
$filename = "mmyexcel.xls";
$objPHPExcel = new PHPExcel();
$sheet = $objPHPExcel->getActiveSheet()->setTitle('Excel Export');
$list[] = $array2;
$sheet->fromArray($list);
header('Content-Type: application/vnd.ms-excel');
//tell browser what's the file name
header('Content-Disposition: attachment;filename="' . $filename . '"');
header('Cache-Control: max-age=0'); //no cache
//save it to Excel5 format (excel 2003 .XLS file), change this to 'Excel2007' (and adjust the filename extension, also the header mime type)
//if you want to save it as .XLSX Excel 2007 format
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
//force user to download the Excel file without writing it to server's HD
$objWriter->save('php://output');
Related
I have a problem like when I download excel sheet after remaining code not executing. Please look below mentioned sample code.
$data[]=array('EANCODE'=>6161106690015,'ItemDesc'=>'Electrical hammer mill 15hp'
,'UnitDesc'=>'PIECES','qty'=>10);
$object = new PHPExcel();
$object->setActiveSheetIndex(0);
$object->getActiveSheet()->setCellValue('A1', "EANCODE");
$object->getActiveSheet()->setCellValue('B1', "Item Name");
$object->getActiveSheet()->setCellValue('C1', 'Units');
$object->getActiveSheet()->setCellValue('D1', 'Quantity');
$excel_row = 2;
foreach($data as $item)
{
$object->getActiveSheet()->setCellValue('A'.$excel_row, $item['EANCODE']);
$object->getActiveSheet()->setCellValue('B'.$excel_row, $item['ItemDesc']);
$object->getActiveSheet()->setCellValue('C'.$excel_row, $item['UnitDesc']);
$object->getActiveSheet()->setCellValue('D'.$excel_row, $item['qty']);
$excel_row++;
}
$store_name='Insertion Failed Records - '. date('d-m-Y').".xlsx";
header('Content-Type: application/vnd.openxmlformats-
officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="'.$store_name.'');
header('Cache-Control: max-age=0');
$objWriter =new PHPExcel_Writer_Excel2007($object, 'Excel2007');
$objWriter->save('php://output');
echo "something else";
Output : Excel Sheet downloading but given echo statement not showing.
To output the XLS sheet to the page you are on, just make sure that page has no other echo's,print's, outputs.
As per my knowledge when we create and download or save file in any directory all echo content before this statement $objWriter->save('php://output'); is written in your file and after that statement, all part is skipped.
I am having issue for days now and couldn't figure out what's the issue. I appreciate any help. So, I am trying to put the total of a column in a cell in an excel file generated using phpexcel however the generated excel gets corrupted everytime I use the function SUM(). Function COUNT(), MIN(), etc. works just fine. The code is as follows:
foreach($data as $d)
{
$col = 0; $field_count = 0;
foreach($d as $cell)
{
$sheet->setCellValueByColumnAndRow($col, $row, $cell);
$col++; $field_count++;
}
$row++;
}
$sheet->setCellValue('E'.$row, 'Grand Total:' );
$sheet->setCellValue('F'.$row, '=SUM(F5:F'.($row-1).')');
//$sheet->setCellValue('G'.$row, '=COUNT(F5:F'.($row-1).')');
$objPHPExcel->setActiveSheetIndex(0);
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="'.$filename.'"');
header('Cache-Control: max-age=0');
$objWriter->save('php://output');
Here's the error I am getting everytime I use SUM:
I am trying to create a xls file in php. And I am making a string in html format lets say <table><tr><td>Cell 1</td><td>Cell 2</td></tr></table> and want to print in xls file as it is. but My problem is that when I try to print in xls file its getting render. but I want raw html string without rendered in xls file.
Here is my code:-
<?php
$file="demo.xls";
$test="<table><tr><td>Cell 1</td><td>Cell 2</td></tr></table>";
header('Content-type: application/excel');
header("Content-Disposition: attachment; filename=$file");
echo $test;
?>php
You can also use a service called DocRaptor which does html to excel conversion. http://docraptor.com/ , Multiple language supported
Or You can use the below code to download the file in Excel but first you have to download the PHPExcel class files and include like below .
require_once "excel/Classes/PHPExcel.php";
$objTpl = new PHPExcel();
$l=0;
$row_num = 1;
$objTpl->getActiveSheet()->getDefaultStyle()->getFont()->setName('Calibri');
$objTpl->getActiveSheet()->getDefaultStyle()->getFont()->setSize(10);
$objTpl->getActiveSheet()->getStyle('A1')->getFont()->setBold(true);
$objTpl->getActiveSheet()->duplicateStyle($objTpl->getActiveSheet()->getStyle('A1'), 'B1:Z1');
$objTpl->getActiveSheet()->getStyle('A1:Z1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
// you can use loop over here remember to set $row_num = 2 if using loop and increment it inside $row_num++
$objTpl->getActiveSheet()->setCellValueByColumnAndRow($l++,$row_num, 'Cell 1');
$objTpl->getActiveSheet()->setCellValueByColumnAndRow($l++,$row_num, 'Cell 2');
$filename='some_file.xls'; //just some random filename
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="'.$filename.'"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objTpl, 'Excel5'); //downloadable file is in Excel 2003 format (.xls)
$objWriter->save('php://output'); //send it to user, of course you can save it to disk also!
exit; //done.. exiting!
There is a way by either writing html in file or comma separated text
With HTML
$xlsx_file = $pathinfo['dirname']."/".$pathinfo['filename'].".xlsx" ;
$fh = fopen($xlsx_file, 'w+');<br>
fwrite($fh, $table); // your table <br>
fclose($fh);<br>
with array or string of csv
$data = '"Name"t"City"t"Country"' . "n";<br>
$data .= '"Ashok"t"New Delhi"t"India"' . "n";<br>
$data .= '"Krishna"t"Bangalore"t"India"' . "n";<br>
$f = fopen('data.xls' , 'wb');<br>
fwrite($f , $data );<br>
fclose($f);<br>
this is temporary solution but if you want full set of options you go for PHP Excel as suggested by others
i have a problem to download excel file. When im saving on server its worked ok. But when i try to download things goes wrong.This is my code:
$result = getSoapResult($soapURL, $soapWSDL, $soapMETHOD, $inputParameters);
header("Content-Type: application/vnd.ms-excel; charset=utf-8");
header('Content-Disposition: attachment;filename="file_name.xls"');
header('Cache-Control: max-age=0');
$objExcel = new PHPExcel();
$objExcel->setActiveSheetIndex(0);
$rowCount = 1;
$column = 'A';
foreach($result as $key => $value){
if($rowCount == 1){
foreach($value as $k => $v){
$objExcel->getActiveSheet()->SetCellValue($column.$rowCount, $k);
$column++;
}
$rowCount++;
}
$column = 'A';
foreach($value as $k => $v){
$objExcel->getActiveSheet()->SetCellValue($column.$rowCount, $v);
$column++;
}
$rowCount++;
}
$objWriter = PHPExcel_IOFactory::createWriter($objExcel, 'Excel2007');
ob_clean();
$objWriter->save('php://output');
it gives an excel file with this content:
I cant find answer from another questions with this problem.
The PK at the begining gives away it's a zip file. Coincidentally, xlsx is a special kind of zip file. Try to save the file as .xlsx instead of .xls and Excel should handle it correctly.
Given you're specifying Excel2007 as the format, you're getting an .xlsx file. If you need a .xls file, maybe you can use Excel2003 instead.
Please add the code before your file download code
ob_end_clean();
ob_start();
I'm stuck with this problem, it's not displaying the actual excel file. Please check my code below:
/** Error reporting */
error_reporting(E_ALL);
/** PHPExcel */
require_once 'PHPExcel.php';
include 'PHPExcel/Writer/Excel2007.php';
// Create new PHPExcel object
#echo date('H:i:s') . " Create new PHPExcel object\n";
$objPHPExcel = new PHPExcel();
$excel = new PHPExcel();
$objPHPExcel->getProperties()->setTitle("Payroll");
if(!$result){
die("Error");
}
$col = 0;
$row = 2;
while($mrow = mysql_fetch_assoc($result)) {
$col = 0;
foreach($mrow as $key=>$value) {
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $value);
$col++;
}
$row++;
}
// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A1', 'Scholar Id')
->setCellValue('B1', 'Lastname')
->setCellValue('C1', 'Middlename')
->setCellValue('D1', 'Firstname')
->setCellValue('E1', 'Barangay')
->setCellValue('F1', 'Level')
->setCellValue('G1', 'Allowance')
->setCellValue('H1', 'Has claimed?');
$objPHPExcel->getActiveSheet()->getStyle('A1:H1')->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(12);
$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(18);
$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(18);
$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(18);
$objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(18);
$objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(12);
$objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(12);
$objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(14);
$objPHPExcel->getActiveSheet()->getStyle('A1:H1')->getAlignment()- >setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
$objPHPExcel->getActiveSheet()->setShowGridlines(true);
$objPHPExcel->getActiveSheet()->getStyle('A1:H1')->applyFromArray(
array(
'fill' => array(
'type' => PHPExcel_Style_Fill::FILL_SOLID,
'color' => array('rgb' => 'FFFF00')
)
)
);
// Save Excel 2007 file
echo date('H:i:s') . " Write to Excel2007 format\n";
#$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="payroll.xlsx"');
header('Cache-Control: max-age=0');
$writer->save('php://output');
I got it working now! Thanks to this phpexcel to download
I changed the code to this:
// Save Excel 2007 file
#echo date('H:i:s') . " Write to Excel2007 format\n";
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
ob_end_clean();
// We'll be outputting an excel file
header('Content-type: application/vnd.ms-excel');
header('Content-Disposition: attachment; filename="payroll.xlsx"');
$objWriter->save('php://output');
I think this line:
ob_end_clean();
solved my problem.
I don't know if i can help i had the same problem and i solved with
ob_end_clean();
i put it just after
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
So don't change the header and save it as xslx anyway, the problem is the buffer!
The most likely culprit if this is a cut-and-paste of your script is the
echo date('H:i:s') . " Write to Excel2007 format\n";
If you're sending to the browser for download, then there must be no other output (echoes, print statements, dropping in and out of PHP) than the output generated to php://output by PHPExcel itself
Please make sure that all files (e.g. that are included) are in UTF-8 without BOM encoding.
You can identify this in different ways, e.g. see this link.
Only if you need UTF-8 with BOM - please use ob_end_clean(); before data outputing to browser, as pointed in other answers here.
I have the same problem, the problem is simple. Just put code below :
ob_end_clean();
after :
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
i think the solution of this problem is the same as here:
Google Chrome errors while exporting XLS file using PHP
just add a space between attachement; and filename, that way :
header("Content-Disposition: attachment; filename=\"Past_Due_Report.xls\"");
as i can see in your own answer that's what you did, and is probably what fixed your problem.
I had the same problem but calling ob_end_clean() didn't work. My CMS (drupal 7) had messed up my headers so I got a new line (hex 0A) at the beginning of the content even if I called ob_end_clean() before the file output.
With the code below I finaly got rid of the leading new line:
for ($i = 0; $i < ob_get_level(); $i++) { ob_end_flush(); }
ob_implicit_flush(1);
ob_clean();
This answer save my life. Thanks #ARN
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, "Excel2007");
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment; filename="export_result.xlsx"');
for ($i = 0; $i < ob_get_level(); $i++) {
ob_end_flush();
}
ob_implicit_flush(1);
ob_clean();
$objWriter->save("php://output");
I have the same problem, but i using library phpspreadsheet
just put this function:
ob_end_clean();
after this code :
$writer = new Xlsx($spreadsheet);