On click of download excel button in my application,i am creating a excel file using PHP EXCEL library.The downloading time is more if data is around like 10,000 rows from database. On click of download I need to display like Please wait x seconds or minutes to download file .My application is in PHP and I am not storing file in my directory.
My code is Like This
$sqlFields = "SELECT * from table_name ORDER BY name";//it gives 10,000 rows
include_once($_SERVER['DOCUMENT_ROOT'] . "/lib/PHPExcel.php");
$objPHPExcel = new PHPExcel();
$objPHPExcel_11 = $objPHPExcel->setActiveSheetIndex(0);
foreach ($sqlFields AS $List) {
//here putting data to excel cells
}
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="Report '.date('Y-m-d H:i:s').'.xls"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
Related
I am converting HTML to excel file.
<?php
header("Content-type: application/vnd.ms-excel; name='excel'");
header("Content-Disposition: attachment; filename=test.xls");
?>
<tr><td>(8.47%)</td></tr>
Here i want to display (8.47%) in display in excel but when i open the excel file it automatically convert and display as -8.47 .
I want my value to be display as (8.47%) not as -8.47.
Does quoting works ? Like you do in excel.
<tr><td>('8.47%)</td></tr>
Edit:
<?php
header("Content-type: application/vnd.ms-excel; name='excel'");
header("Content-Disposition: attachment; filename=test.xls");
?>
<table>
<tr><td>(8.47%)</td></tr>
</table>
I just add <table></table> around and works for me
I have problem. I created a web page with upload files, I have database (MySQL) with correctly URL to file (file path) (in database is only url to the file, file is in folder on the server). And now I trying write/search php script to download this file what was uploaded. All at web works well, but this download scripts don't work. I read and I think best way for me will be download with 'header', but I was trying and nothing. File is download to our disk, name is correctly, file extension ok, file is open in correct program, but if file have in name chars (';',':' etc.) file is download without these chars and is incorrectly (lack of extension, bad name). And second problem: all downloaded files are empty (0 b size), all is ok but they are empty, some tips ? Thanks in advance for help
My bad download codes:
<?php
$data=date('Y-m-d_H:i:s');
$nazwa=$_POST['downtitle'];
$urlek=$_POST['downurl'];
$extrozsz=$_POST['downext'];
$filePath = $urlek;
$fileName = $nazwa.$data.".".$extrozsz;
//------------------------------------------------------------------------
// $fd = fopen($filePath,"r");
// $size = filesize($filePath);
// $contents = fread($fd, filesize($filePath));
// fclose($fd);
// header("Content-Type: application/octet-stream");
// header("Content-Length: $size;");
// header("Content-Disposition: attachment; filename=$fileName");
// echo $contents;
//----------------------------------------------------------------------
// set_time_limit(0);
// while( $urlek = $response->fetch() )
// {
// $my_pliki = file_get_contents("$urlek");
// $my_file = fopen("$urlek","w+");
// fwrite($my_file,$my_pliki);
// fclose($my_file);
// }
//----------------------------------------------------------------------------
$quoted = $filePath;
$size = filesize($file);
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . $quoted);
header('Content-Transfer-Encoding: binary');
header('Connection: Keep-Alive');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . $size);
?>
The filename parameter has some limits which are well described in RFC6266
So when you want use characters that are not present in the ISO-8859-1 character set then you need to use either filename* header or you need to strip/replace these characters from the filename. Nice solution to do so can be found here
Ok all is now ok, but another problem. I have code for showing news at website. All news are showing at same time (too long site). I wish to have at bottom of website numbers (at all websites under are this for forwarding on second subpage with older news). But how do it? Sup or sub is for small word, numbers etc, but all is retrieved form database:
$zapytanie='SELECT * FROM filetable WHERE Section="Other" ORDER BY ID DESC LIMIT 10';
This is in my php code query for showing latest 10 news, but if I add normally small numbers at bottom how construct code for showing next 10 news (no at where id="10-11" because if I will be have 1 thousand news or more it is too primitive) I must have automated code for showing pages with nextly 10 or 20 news how ?
Thanks, I edit my php at this:
<?php
$data=date('Y-m-d_H:i:s');
$nazwa=$_POST['downtitle'];
$urlek=$_POST['downurl'];
$extrozsz=$_POST['downext'];
$filePath = $urlek;
$fileName = $nazwa.$data.".".$extrozsz;
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/force-download");
header("Content-Disposition: attachment; filename=\"" . $fileName."\"");
header("Content-Description: File Transfer");
readfile($filePath);
?>
And all is now ok, but I have one question now: In MySQL database I have title, description, added date, premiere date and I wish to have search field. I done it in input type="search", but what script now use for searching in this specified tables in database, firstly open database this I know, but what later what command is for search in database ? I know about 'like' but some better? And after all return correct result and show all from database where this search word is ok Some tips? Sorry for weak english and thanks.
I am new to PHP and trying to export some DB data to Excel file as below. But in the output I want the column widths to be adjusted automatically to view the entire content. See the code I am using to export data. I am not using any third party libraries for export.
<?php
require_once("db.php");
$contents="email,time_in,v_id,time_out\n";
$user_query = mysql_query('SELECT * FROM table');
while($row = mysql_fetch_array($user_query))
{
$contents.=$row['email'].",";
$contents.=$row['time_in'].",";
$contents.=$row['v_id'].",";
$contents.=$row['time_out']."\n";
}
// remove html and php tags etc.
$contents = strip_tags($contents);
//header to make force download the file
header("Content-Disposition: attachment; filename=Report".date('d-m-Y').".xls");
print $contents;
?>
Is there any way to format the output ?
I am exporting the results of a query from SQL Server. I half successful in doing it coz I have 1 problem. The HTML codes or interface of the page gets included in the exported .csv file. How do I remove it from the exported file? I have the codes below to give you an idea :)
Also, if you have other tips on how can I improve this thing, like I
want it to be in Excel Format (xlsx), please guide me :)
<html>
<head>
<title>Generate Report</title>
<script>
function MessageBox()
{
alert('Clicked!');
}
</script>
</head>
<body>
<form method='post'>
<input type='date' name='dateStart'> <input type='date' name='dateEnd'>
<input type='submit' name='btnSubmit' onclick='MessageBox()'> <br>
</form>
</body>
</html>";
<?php
include "db.php";
$con = SetConn();
if(isset($_POST['btnSubmit']))
{
header("Content-type: text/csv; charset=UTF-8");
header('Content-Disposition: attachment; filename=Export.csv');
$start = $_POST['dateStart'];
$end = $_POST['dateEnd'];
$user_query = sqlsrv_query($con, "SELECT TOP 100 * FROM [db_nps].[dbo].[survey_report] WHERE (time_stamp >= '$start' and time_stamp <= '$end')");
//While loop to fetch the records
$contents = "it_id, it_site, it_oraclenumber, it_lastname, it_firstname, ttsd_number\n";
while($row = sqlsrv_fetch_array($user_query, SQLSRV_FETCH_ASSOC))
{
$contents.=$row['it_id'].",";
$contents.=$row['it_site'].",";
$contents.=$row['it_oraclenumber'].",";
$contents.=$row['it_lastname'].",";
$contents.=$row['it_firstname'].",";
$contents.=$row['ttsd_number']."\n";
}
$contents_final = chr(255).chr(254).mb_convert_encoding($contents, "UTF-16LE","UTF-8");
print $contents_final;
}
?>
You are telling PHP to use everything echoed as the content for your CSV file. Yes, you are doing so after you echo your HTML, but it doesn't matter; it is all processed at the same time.
Let me Explain:
When you use the header() method, you are telling the browser that the content it is receiving is of a certain type. In your case, you are telling it that the content it is to receive is a CSV document that it should download.
It does not matter where header() is placed within the file, as long as it is before the print or readFile statements.
So essentially what your browser is doing is reading the entirety of the page, including the HTML as plain text for a CSV document. Remember that while PHP will process itself in order, the browser receives all of the information from the server at the same time, and since you are telling it to download the document as a CSV, it takes the whole page.
So what do you do?
My advice to you is to put the printing code in a separate external PHP document and link to it, rather than trying to do it on a page that echoes HTML.
I solved the problem.Try to use your code like this
$filename = 'trip_data.csv';
// file creation
$file = fopen($filename,"w");
// output the column headings
fputcsv($file, array('travel date', 'travel time', 'travel from', 'travel to','number of pessengers', 'car type', 'trip status', 'flight number', 'travel price( £ )'));
$query = "SELECT travel_date,travel_time,travel_from,travel_to,number_of_pessengers,car_type_id,trip_status ,flight_number,travel_price FROM trip";
$travelList = $conn->query($query);
while ($rowValue = $travelList->fetch_assoc()) {
fputcsv($file,$rowValue);
}
fclose($file);
// download
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$filename");
header("Content-Type: application/csv; ");
readfile($filename);
// deleting file
unlink($filename);
exit();
I have a web page where a user selects the amount of rows to be displayed followed by a button within a form that exports the data to excel.
<form method="post" action="">
<input type="Submit" name="excel" value="Export" class="button">
</form>
I am able to get the data and put it into the excel file with the follwoing
if($_POST['excel']){
$phpExcel = new PHPExcel();
$styleArray = array(
'font' => array(
'bold' => true,
)
);
//Get the active sheet and assign to a variable
$foo = $phpExcel->getActiveSheet();
//add column headers, set the title and make the text bold
$foo->setCellValue("A1", "Nombre")
->setCellValue("B1", "Paterno")
->setCellValue("C1", "Pkey")
->setCellValue("D1", "Telefono")
->setCellValue("E1", "Ciudad")
->setCellValue("F1", "Used")
->setTitle("Contactos Encuestas")
->getStyle("A1:F1")->applyFromArray($styleArray);
$xlsRow = 1;
foreach ($rows as $column) {
$foo->setCellValue("A".$xlsRow++, $column[2])
->setCellValue("B".$xlsRow++, $column[3])
->setCellValue("C".$xlsRow++, $column[0])
->setCellValue("D".$xlsRow++, $column[1])
->setCellValue("E".$xlsRow++, $column[5])
->setCellValue("F".$xlsRow++, $column[4]);
}
header("Content-Type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=\"ENcuestas_Contactos.xls\"");
header("Cache-Control: max-age=0");
$objWriter = PHPExcel_IOFactory::createWriter($phpExcel, "Excel5");
$objWriter->save("php://output");
$phpExcel->disconnectWorksheets();
unset($phpExcel);
}
This kinda works, the issue is that weird text allong with the webpage elements such as buttons and images get put onto the excel file.
What could be the issue?
is there a setting i'm missing?
Found out why I was getting HTML elements in the excel file.
I had the PHP code within the HTML.
Put the PHP Code outside the <html> code and voilà my excel file displayed without any issues.