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.
Related
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');
I'm really really new to PHP, so if you can explain it to me what my code is actually doing and why the result is what it is I would appreciate very much. I'm probably screwing up something very simple.
Basically I want to query a MySQL database, create a csv with the data, and download the csv. Pretty simple. Here is my code:
<?php
include("Includes/PHPheader.php");
$query_string = $_SERVER['QUERY_STRING'];
parse_str($query_string);
$sql = "SELECT many_columns_i_removed_from_this_sample_code FROM table WHERE id = '".$id."'";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
$f = fopen("csv/tmp.csv", "w");
fputcsv($f, array_keys($row),';');
fputcsv($f,$row,';');
rewind($f);
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename="tmp.csv"');
fpassthru($f);
fclose($f);
?>
There are some HTML code below it that shouldn't affect anything, but just in case here it is.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
</body>
</html>
Well, I thought this would download my csv with no problem. If I go to the csv folder, there it is, the tmp.csv file I created, with the proper header and data.
But when I open the tmp.csv file I downloaded, it is actually the html code of the page, and not the data I expected.
What is going on?
In case it helps, I'm using WebMatrix 3.0.
There are two things going on, probably. First, You are trying to read (fpassthru) from a file opened for writing (fopen(..., "w")), so You are not able to read anything from the file. Then, after that "reading nothing" goes Your HTML code, which naturally appends to Your output. Try this:
$f = fopen("csv/tmp.csv", "w+");
...
fclose($f);
exit;
Could you please try?
header("Content-type: application/vnd.ms-excel");
instead of
header('Content-Type: application/csv');
I have a test code of CSV output, have a look - https://foowms.googlecode.com/svn/trunk/stockincsv.php
A very informative thread of Stack Overflow
Setting mime type for excel document
==============================================
If csv file open, write and save, then you should do as follows-
$list = array ("Peter,Griffin,Oslo,Norway");
$file = fopen("csv/tmp.csv","w");
foreach ($list as $line) {
fputcsv($file,explode(',',$line));
}
fclose($file);
==============================================
You also could try this
fputcsv($fp, array_values($list), ';', ' ');
instead of
fputcsv($f, array_keys($row),';');
I am working on a complex program that deals with Excel, so I am using PHPExcel to search and edit the Excel file from a browser. My problem comes in the editing portion of the program, so I wrote a basic program to edit the existing Excel page. It seems that PHPExcel does not recognize the file created in Excel as an Excel file. This is done on my own server with an Excel page I created with Excel. The filename is 062014.xlsx. On the HTML side I named the text boxes C3, D3, and E3, so their names will easily correspond with Excel cells ( where the php $cell variable comes from). What I want to do is take the text in the html text boxes and rewrite corresponding cells in Excel with the data from the html textboxes. Posted is my whole code from html and php, if someone can tell me where my program is going wrong, I would greatly appreciate it.
<html>
<head>
<form method="POST" action="lilrevisetest.php" id="excelform">
<input type="text" value="foo" name="C3" />
<input type="text" value="foo" name="D3" />
<input type="text" value="foo" name="E3" />
<button type="submit">Submit</button>
</form>
</body>
</html>
<body>
<html>
<?php
include 'PHPExcel/IOFactory.php';
$n=1;
$x="C";
$y=1;
$file = "062014.xlsx";
$inputFileType = PHPExcel_IOFactory::identify($file);
$inputFileType = 'Excel5';
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objReader->setReadDataOnly(false);
$objPHPExcel = $objReader->load($file);
$objWorksheet = $objPHPExcel->getActiveSheet();
$fileObj = fopen("$file", "rt" );
$y = 3;
$x= "C";
for($n=1; $n<4; $n++){
$cell = $x . $y;
echo $cell;
if (isset($_POST[$cell])){
$string = ($_POST[$cell]);
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, $inputFileType);
$objWorksheet ->setCellValue("$cell","$string");
$objWriter->save($file);
}
echo "<td> <input type ='text' value= '$string' name = '$cell'/></td>";
$x= ++$x;
}
?>
</html>
</body>
You are trying to load an xlsx file (OfficeOpenXML-format) using the Excel5 (BIFF-format) Reader.
$inputFileType = 'Excel5';
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
You should be using the correct Reader for the file type you're trying to load, otherwise you will get errors.
You've already used
$inputFileType = PHPExcel_IOFactory::identify($file);
to identify the filetype and the correct Reader to use, so why are you ignoring this and setting it manually (and incorrectly) yourself?
Additionally
Another problem is likely to be the fact that the file is already open when you try to save it.
You're loading $file (062014.xlsx) using the PHPExcel loader, no problem.
For some unknown reason, you then execute
$fileObj = fopen("$file", "rt" );
though you don't do anything with $fileObj at all, but doing this leaves it open
When you try to save using $objWriter->save($file);, the file is still held open, so the save will fail (nothing to do with the filename, simply the fact that the file is open).
The solution is as simple as deleting the line
$fileObj = fopen("$file", "rt" );
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();