Create XLS file from MySQL database using PHP script - php

I want to generate XLS files with a PHP script from a MySQL database. The big problem here is that when I open the new exported .xls file, I see the values OK (i.e. it is correctly formatted) but the colour of the field changed to white. However, I need the colour unchanged, as is by default in Excel.
Here is the PHP script that I use to extract data from my database.
<?php
include 'connect.php';
$result = mysql_query('SELECT * FROM projects2');
?>
<center><h1>Lista valorilor din tabela</h1>
<h2>Exporta lista Clienti</h2></center>
<?php
include_once 'tabel_clientipm.php';
?>
The PHP file used to generate the XLS file is:
<?php
include 'connect.php';
$result = mysql_query('SELECT * FROM projects2');
if (isset($_GET['exporta_lista_clienti'])) {
$filename = 'raportnou.xls';
header("Content-type: application/ms-excel");
header("Content-Disposition: attachment; filename=$filename");
include_once 'tabel_clientipm.php';
exit();
}
?>
I added the tabel_clientipm.php:
<center>
<table border="1">
<tr>
<th>surname</th>
<th>name</th>
<th>age</th>
</tr>
<?php
while ($client = mysql_fetch_assoc($result)) {
?>
<tr>
<td><?php echo $client['surname'];?></td>
<td><?php echo $client['name'];?></td>
<td><?php echo $client['age'];?></td>
</tr>
<?php
}
?>
</table>
</center>

If you want to create real .xls file NOT csv or html hidden in .xls extension use PHPExcel or
It supports the following formats.
BIFF 8 (.xls) Excel 95 and above
Office Open XML (.xlsx) Excel 2007 and above
If PHPExcel is slow for you check these alternatives (provided by an author of PHPExcel. All of them are faster than PHPExcel

If you export as a csv, you can probably import the data as colorless.

Related

Downloading pdf file directly from database

Im trying to allow my user to download the file that they select in my system. The code i have used downloads something but it says failed forbidden. I haven't used directories to store the files but rather stored the file in a longblob data type directly in the database. If someone could please show me how to get it to download successfully I would appreciate it.
<tbody>
<?php
require_once 'dbcon.php';
$query = $conn->query("SELECT fileID, filename, file, dateuploaded from empfiles WHERE eemail = '$_SESSION[login_employee]'");
$count = 1;
while($fetch = $query->fetch_array()){
?>
<tr>
<td style="height:50px;width:100px"><?php echo $count++?></td>
<td style="height:50px;width:200px"><?php echo $fetch['filename']?></td>
<td style="height:50px;width:100px"><?php echo $fetch['dateuploaded']?></td>
?>
</td>
<td colspan="2">
<td>
echo"<a download href=\"file/{$row['file']}\">Download this file</a>";
</td>
</tr>
<?php
}
?>
</tbody>
The value of the href attribute needs to be a URL.
You can't just take a blob of PDF out of the database and coerce it into a string.
You need to either base64 encode it and then convert it to a data URL (noting that there is a good change this will result in a URL that is too long for the browser to accept).
or
Create a new webservice that extracts the PDF from the database and generates the download based on, for example, the row id. Then link to that webservice with the row id in the query string.

Convert a "String" to "Float" exporting to EXCEL in HTML and PHP

I am exporting an HTML table to excel.
But when I want to export a number with decimals (float / double) that contain a point
20.02 < "."
The excel thinks that it is a string, no matter what type it is (because I've done a gettype and it shows me double), just because it contains the point it reads it as a string.
Im using next code:
$filename = "filename.xls";
header('Content-Type: content=text/html; charset=ISO-8859-1');
header("Content-type: application/x-msdownload");
header("Content-Disposition: attachment; filename=$filename");
Then table: (this is a example)
<table>
<tr>
<th>Float</th>
</tr>
<tr>
<td> <?php echo utf8_decode($float) ?></td>
</tr>
</table>
All the code works, I export a perfect excel, just as I want, the only problem I find is the conversion of the float that HTML reads as a STRING when reading a
" . "

php mysql export should create dropdown

I'm trying to make a .xls export from a part of my mysql database. I came up with the following sollution:
//Get the data from database and write it to a table
$siteNumber = 999;
$results = Db::getInstance()->queryResults('SELECT * FROM `configurations`');
?>
<table border="1">
<tr>
<th>Configuration id</th>
<th>Configuration category</th>
<th>Configuration name</th>
</tr>
<?php
foreach($results as $result => $key) {
$str = '<tr>';
$str .= '<td>'.$key->configuration_id .'</td>';
$str .= '<td>'.$key->configuration_category .'</td>';
$str .= '<td>'.$key->configuration_name .'</td>';
$str .= '</tr>';
echo $str;
}
?>
</tr>
</table>
//And I use header to create a excelfile
<?php
// Add data table
include 'exceldata.php';
// The function header by sending raw excel
header("Content-type: application/vnd-ms-excel");
// Defines the name of the export file "codelution-export.xls"
header("Content-Disposition: attachment; filename=test.xls");
?>
This all works fine and outputs a nice table. What I'm trying to achieve is all results get exported classified by configuration_category as dropdown.
Is there any way to do this?
Thanks in advance!
I'm not sure i understand. ButIf you want to exprt the exelfile with included dropdown you can just make use of html with unordered list
I guess this: https://github.com/PHPOffice/PHPExcel is what you need.
PHPExcel will allow you to create beautiful spreadsheets and export them into Excel format.
You can create Excel DropDowns using this library as well. See this page for details: Read the list of options in a drop-down list - Phpexcel

code to expand excel column width in php while exporting

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 ?

HTML codes always showing up when I export query result to Excel CSV

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

Categories