Print raw html to xls file in php - php

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

Related

Export Multi-Dimensional Array Data into Excel in PHP

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

PHPExcel Export HTML String is Exporting Entire HTML Page

I have a table on an html page that I need to export. I have searched other examples on here but nothing that works for me.
Here is what I have.
$filename = "DownloadReport";
//$table = dbGrid($q);
$table = "<div><table><tbody><tr><td>cars</td><td>cars</td><td>cars</td></tr></tbody></table></div>";
$tmpfile = tempnam(sys_get_temp_dir(), 'html');
file_put_contents($tmpfile, $table);
$excelHTMLReader = PHPExcel_IOFactory::createReader('HTML');
$objPHPExcel = $excelHTMLReader->load($tmpfile);
$objPHPExcel->getActiveSheet()->setTitle('anynameyouwant');
unlink($tmpfile);
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="' . $filename . '-' . date("y.m.d") . '.xlsx"');
header('Cache-Control: max-age=0');
$writer = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$writer->save('php://output');
exit;
It properly downloads the file. But for some reason its saving my entire html page with javascript and css files missing. I only need to export the table string. I have a dbGrid function to create my table but for testing I have a simple table string.
How can I export just that table string, not my entire html page.

PHP fails to download Excel file that is generated by PHP Excel

I want to download excel file (instead of saving it). Since I want to export HTML table I am using PHPExcel_reader_HTML to read contents of HTML table. Excel file is created perfectly when I want to save it but when I want to download it, nothing happens. Does someone knows where's the problem?
Code:
<?php
// Load the table view into a variable
$html = $_POST["table"];
require_once('php/PHPExcel/Classes/PHPExcel.php');
// Put the html into a temporary file
$objPHPExcel = new PHPExcel();
$tmpfile = time().'.html';
file_put_contents($tmpfile, $html);
// Read the contents of the file into PHPExcel Reader class
$reader = new PHPExcel_Reader_HTML;
$content = $reader->load($tmpfile);
// Pass to writer and output as needed
$objWriter = PHPExcel_IOFactory::createWriter($content, 'Excel2007');
header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
header("Content-Disposition: attachment; filename=\"results.xlsx\"");
header("Cache-Control: max-age=0");
$objWriter->save("php://output");
ob_clean();
// Delete temporary file
unlink($tmpfile);
?>

Using phpexcel to export MySql to excel

Hi everyone I have created a program to export MySQL data to excel but at some point I am getting the error the time I am trying to open the excel file.
The error: The file you are trying to open is in a different format,than specified by the file extension.Verify that the file is not corrupt and is from the trusted source before opening the file.Do you want to open the file now?
When I click yes i get the some funny characters on that excel file.
Here is my code:
include 'setup.php';
_connectsurvey(); //Database
require_once 'PHPExcel.php';
$objPHPExcel = new PHPExcel();
$query = "SELECT * FROM questionanswer";
$result = mysql_query($query) or die(mysql_error());
$objPHPExcel = new PHPExcel();
$rowCount = 1;
while($row = mysql_fetch_array($result)){
$objPHPExcel->getActiveSheet()->SetCellValue('A'.$rowCount, $row['gender']);
$objPHPExcel->getActiveSheet()->SetCellValue('B'.$rowCount, $row['city']);
$rowCount++;
pr($objPHPExcel);
}
header('Content-Type: application/vnd.openxmlformats- officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="survey.xls"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');
Near the bottom when you name the file use file extension .xlsx it is the proper file extension for openxml based documents from office 2007 should fix your issue.
header('Content-Disposition: attachment;filename="survey.xlsx"');
If you absolutely need to use xls change the output type to Excel2003 but then you need to change the content type header to match that as well.

Saving Generated CSV to Server in Proper format as download

I've have been successful in exporting my database to csv as a downloadable file. However what I now need to do is instead of creating a straight .csv file that's downloaded I need it to just save to a folder called "csv" on the server. Here is my code for the current export. I need help in the saving it to server. I'm not saving the data correctly.
// output headers so that the file is downloaded rather than displayed
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data.csv');
// create a file pointer connected to the output stream
$output = fopen('php://output', 'w');
// output the column headings
fputcsv($output, array('tax_class_id','_product_websites'));
// fetch the data
mysql_connect('localhost:3036', 'x', 'x');
mysql_select_db('lato');
$rows = mysql_query('SELECT taxclass,productwebsite FROM product');
// loop over the rows, outputting them
while ($row = mysql_fetch_assoc($rows))
fputcsv($output, $row);
$filename = "data.csv"; // Trying to save file in server
file_put_contents("download/" . $filename, "$header\n$rows");
You need to change your last line to
$filename = "data.csv"; // Trying to save file in server
file_put_contents("download/" . $filename, $output);

Categories