In my php page i have a table and if the user requires he has to export that table to excel sheet..
The code for displaying the table is:
$sql=mysql_query("SELECT * FROM attendance WHERE (year = '" .
mysql_real_escape_string($_SESSION['year']) . "') and ( branch= '" .
mysql_real_escape_string(($_SESSION['branch'])). "') and ( sem= '" .
mysql_real_escape_string(($_SESSION['sem'])). "') and (sec= '" .
mysql_real_escape_string(($_SESSION['sec'])). "')"); print "<body
background='bg.jpg'>";
Print "<br><br><BR><center><table border
cellpadding=3><tr><th>idno</th><th>name</th><th>subject</th><th>Held
Classes</th><th>Attended Classes</th></tr>";
while($data=mysql_fetch_array(
$sql )) {
echo "<tr><td>".$data['idno']." </td><td>".$data['name'] . "
<td>".$data['subject']." </td><td>".$data['heldcls'] . "
<td>".$data['attendcls']." </td>"; }
Print "</table><br><br><form action = excel.php method = POST><input type =
'submit' name = 'submit' Value = 'Export to excel'></form></center>";
how do i export this table to excel sheet. And what should b the code in excel.php. Please help me.. thank you in advance..
asked Sep 22, 2012 at 5:28
1
Either you can use CSV functions or PHPExcel
or you can try like below
<?php
$file="demo.xls";
$test="<table ><tr><td>Cell 1</td><td>Cell 2</td></tr></table>";
header("Content-type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=$file");
echo $test;
?>
The header for .xlsx files is Content-type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
Isaac
6251 gold badge13 silver badges30 bronze badges
answered Sep 22, 2012 at 5:31
NullPoiиteяNullPoiиteя
56.2k22 gold badges125 silver badges143 bronze badges
2
If all you want is a simple excel worksheet try this:
header('Content-type: application/excel');
$filename = 'filename.xls';
header('Content-Disposition: attachment; filename='.$filename);
$data = '<html xmlns:x="urn:schemas-microsoft-com:office:excel">
<head>
<!--[if gte mso 9]>
<xml>
<x:ExcelWorkbook>
<x:ExcelWorksheets>
<x:ExcelWorksheet>
<x:Name>Sheet 1</x:Name>
<x:WorksheetOptions>
<x:Print>
<x:ValidPrinterInfo/>
</x:Print>
</x:WorksheetOptions>
</x:ExcelWorksheet>
</x:ExcelWorksheets>
</x:ExcelWorkbook>
</xml>
<![endif]-->
</head>
<body>
<table><tr><td>Cell 1</td><td>Cell 2</td></tr></table>
</body></html>';
echo $data;
The key here is the xml data. This will keep excel from complaining about the file.
answered Mar 28, 2013 at 18:26
darkratdarkrat
6736 silver badges14 bronze badges
4
<script src="jquery.min.js"></script>
<table border="1" id="ReportTable" class="myClass">
<tr bgcolor="#CCC">
<td width="100">xxxxx</td>
<td width="700">xxxxxx</td>
<td width="170">xxxxxx</td>
<td width="30">xxxxxx</td>
</tr>
<tr bgcolor="#FFFFFF">
<td><?php
$date = date_create($row_Recordset3['fecha']);
echo date_format($date, 'd-m-Y');
?></td>
<td><?php echo $row_Recordset3['descripcion']; ?></td>
<td><?php echo $row_Recordset3['producto']; ?></td>
<td><img src="borrar.png" width="14" height="14" class="clickable" onClick="eliminarSeguimiento(<?php echo $row_Recordset3['idSeguimiento']; ?>)" title="borrar"></td>
</tr>
</table>
<input type="hidden" id="datatodisplay" name="datatodisplay">
<input type="submit" value="Export to Excel">
exporttable.php
<?php
header('Content-Type: application/force-download');
header('Content-disposition: attachment; filename=export.xls');
// Fix for crappy IE bug in download.
header("Pragma: ");
header("Cache-Control: ");
echo $_REQUEST['datatodisplay'];
?>
answered Jul 28, 2014 at 15:28
Easiest way to export Excel to Html table
$file_name ="file_name.xls";
$excel_file="Your Html Table Code";
header("Content-type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=$file_name");
echo $excel_file;
answered Oct 22, 2019 at 9:23
Love KumarLove Kumar
1,0409 silver badges10 bronze badges
2
Export Data to Excel is a popular feature of web applications to allow dynamic data export to Excel file to save locally for further use. If you’re a PHP developer and thinking to implement data export to excel, then you’re here at right place. You will learn here how to implement data export to excel using PHP & MySQL.
In our previous tutorial you have learned how to export data to excel in CodeIgniter, now in this tutorial we will explain how to export data to excel with PHP and MySQL.
We will cover this tutorial step by step to create live demo to implement data export to excel with PHP and MySQL. You can also download complete source code of live.
Also, read:
- Export Data to Excel with PhpSpreadsheet using CodeIgniter
- Export Data to CSV File with PHP and MySQL
- Export HTML Table Data to Excel, CSV and Text with jQuery, PHP and MySQL
So let’s start implementing data export to excel with PHP and MySQL. Before we begin, take a look on files structure for this example.
- index.php:
- export.php:
Step1: Create MySQL Database Table
As we will cover this tutorial with example to export data to Excel file, so first we will create MySQL database table developers
to store developer records.
CREATE TABLE `developers` ( `id` int(11) NOT NULL, `name` varchar(255) NOT NULL, `skills` varchar(255) NOT NULL, `address` varchar(255) NOT NULL, `gender` varchar(255) NOT NULL, `designation` varchar(255) NOT NULL, `age` int(11) NOT NULL, `image` varchar(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
We will also insert few records to this table.
INSERT INTO `developers` (`id`, `name`, `skills`, `address`, `gender`, `designation`, `age`, `image`) VALUES (1, 'Smith', 'Java', 'Newyork', 'Male', 'Software Engineer', 34, 'image_1.jpg'), (2, 'David', 'PHP', 'London', 'Male', 'Web Developer', 28, 'image_2.jpg'), (3, 'Rhodes', 'jQuery', 'New Jersy', 'Male', 'Web Developer', 30, 'image_2.jpg'), (4, 'Sara', 'JavaScript', 'Delhi', 'Female', 'Web Developer', 25, 'image_2.jpg'), (5, 'Shyrlin', 'NodeJS', 'Tokiyo', 'Female', 'Programmer', 35, 'image_2.jpg'), (6, 'Steve', 'Angular', 'London', 'Male', 'Web Developer', 28, 'image_2.jpg'), (7, 'Cook', 'MySQL', 'Paris', 'Male', 'Web Developer', 26, 'image_2.jpg'), (8, 'Root', 'HTML', 'Paris', 'Male', 'Web Developer', 28, 'image_2.jpg'), (9, 'William', 'jQuery', 'Sydney', 'Male', 'Web Developer', 23, 'image_2.jpg'), (10, 'Nathan', 'PHP', 'London', 'Male', 'Web Developer', 28, 'image_2.jpg'), (11, 'Shri', 'PHP', 'Delhi', 'Male', 'Web Developer', 38, 'image_2.jpg'), (12, 'Jay', 'PHP', 'Delhi, India', 'Male', 'Web Developer', 30, 'image_3.jpg');
Step2: Get Records from MySQL Database Table
In export.php
file, we will get developer records from MySQL database table developers
and store into an array.
include_once("db_connect.php"); $sqlQuery = "SELECT name, gender, age, skills, address, designation FROM developers LIMIT 10"; $resultSet = mysqli_query($conn, $sqlQuery) or die("database error:". mysqli_error($conn)); $developersData = array(); while( $developer = mysqli_fetch_assoc($resultSet) ) { $developersData[] = $developer; }
Step3: Display Records with Export to Excel Button
In index.php
file, we will display developer records from $developersData
array. We will also add data export button to export data.
<div class="container"> <div class="well-sm col-sm-12"> <div class="btn-group pull-right"> <form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post"> <button type="submit" id="dataExport" name="dataExport" value="Export to excel" class="btn btn-info">Export To Excel</button> </form> </div> </div> <table id="" class="table table-striped table-bordered"> <tr> <th>Name</th> <th>Gender</th> <th>Age</th> <th>Skills</th> <th>Address</th> <th>Designation</th> </tr> <tbody> <?php foreach($developersData as $developer) { ?> <tr> <td><?php echo $developer ['name']; ?></td> <td><?php echo $developer ['gender']; ?></td> <td><?php echo $developer ['age']; ?></td> <td><?php echo $developer ['skills']; ?></td> <td><?php echo $developer ['address']; ?></td> <td><?php echo $developer ['designation']; ?></td> </tr> <?php } ?> </tbody> </table> </div>
Step4: Implement Data Export to Excel
Now we will implement export data to excel when export button clicked. We will use $developersData
array for data exported and saved into an xlsx file.
<?php if(isset($_POST["dataExport"])) { $fileName = "webdamn_export_".date('Ymd') . ".xls"; header("Content-Type: application/vnd.ms-excel"); header("Content-Disposition: attachment; filename="$fileName""); $showColoumn = false; if(!empty($developersData)) { foreach($developersData as $developerInfo) { if(!$showColoumn) { echo implode("t", array_keys($developerInfo)) . "n"; $showColoumn = true; } echo implode("t", array_values($developerInfo)) . "n"; } } exit; } ?>
You may also like:
- User Management System with PHP & MySQL
- Datatables Add Edit Delete with Ajax, PHP & MySQL
- Build Helpdesk System with jQuery, PHP & MySQL
- Build Online Voting System with PHP & MySQL
- School Management System with PHP & MySQL
- DataTables Add Edit Delete with CodeIgniter
- Create RESTful API using CodeIgniter
- Build Reusable Captcha Script with PHP
- Product Search Filtering using Ajax, PHP & MySQL
- Image Upload and Crop in Modal with jQuery, PHP & MySQL
- Build Push Notification System with PHP & MySQL
- Project Management System with PHP and MySQL
- Hospital Management System with PHP & MySQL
- Build Newsletter System with PHP and MySQL
- Skeleton Screen Loading Effect with Ajax and PHP
- Build Discussion Forum with PHP and MySQL
- Customer Relationship Management (CRM) System with PHP & MySQL
- Online Exam System with PHP & MySQL
- Expense Management System with PHP & MySQL
You can view the live demo from the Demo link and can download the script from the Download link below.
Demo Download
Export data feature is very useful where the data is saved on the local drive for offline uses. Export data to file functionality provides a user-friendly way to maintain a large number of data in the web application. There are various file formats are available to export data and download it as a file. Microsoft Excel is a widely used spreadsheet format that organizes and maintains data.
Generally, export data functionality is used in the data management section of the web application. Excel is the best format to export data in a file and you can easily export data to excel using PHP. In this tutorial, we will show you how to export data to Excel in PHP.
The example PHP script lets you integrate export data to excel functionality. With one click, the user can export data from the MySQL database to Excel and download it in MS Excel file format (.xls/.xlsx).
Export Data to Excel with PHP
In this example script, we will export data from the array (defined in the script) to an excel file.
The $data
variable holds the data in array format which will be exported to Excel using PHP.
$data = array(
array("NAME" => "John Doe", "EMAIL" => "john.doe@gmail.com", "GENDER" => "Male", "COUNTRY" => "United States"),
array("NAME" => "Gary Riley", "EMAIL" => "gary@hotmail.com", "GENDER" => "Male", "COUNTRY" => "United Kingdom"),
array("NAME" => "Edward Siu", "EMAIL" => "siu.edward@gmail.com", "GENDER" => "Male", "COUNTRY" => "Switzerland"),
array("NAME" => "Betty Simons", "EMAIL" => "simons@example.com", "GENDER" => "Female", "COUNTRY" => "Australia"),
array("NAME" => "Frances Lieberman", "EMAIL" => "lieberman@gmail.com", "GENDER" => "Female", "COUNTRY" => "United Kingdom")
);
The filterData()
function is used to filter string before added to the excel sheet row.
function filterData(&$str){
$str = preg_replace("/t/", "\t", $str);
$str = preg_replace("/r?n/", "\n", $str);
if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
}
The following code helps to export data in excel and download it as a file.
- The
$fileName
variable defines the name of the excel file. - The Content-Disposition and Content-Type headers force the excel file to download.
- Run the loop through each key/value pair in the
$data
array. - Display column names as the first row using the
$flag
variable. - The PHP array_walk() function is used to filter the data together with
filterData()
function.
// Excel file name for download
$fileName = "codexworld_export_data-" . date('Ymd') . ".xlsx"; // Headers for download
header("Content-Disposition: attachment; filename="$fileName"");
header("Content-Type: application/vnd.ms-excel"); $flag = false;
foreach($data as $row) {
if(!$flag) {
// display column names as first row
echo implode("t", array_keys($row)) . "n";
$flag = true;
}
// filter data
array_walk($row, 'filterData');
echo implode("t", array_values($row)) . "n";
}exit;
Export Data from Database to Excel with PHP and MySQL
In this example script, we will export data from the MySQL database in an excel file using PHP.
Create Database Table:
For this example, we will create a members
table with some basic fields in the MySQL database. The members
table holds the records which will be exported to excel.
CREATE TABLE `members` ( `id` int(11) NOT NULL AUTO_INCREMENT, `first_name` varchar(25) COLLATE utf8_unicode_ci NOT NULL, `last_name` varchar(25) COLLATE utf8_unicode_ci NOT NULL, `email` varchar(50) COLLATE utf8_unicode_ci NOT NULL, `gender` enum('Male','Female') COLLATE utf8_unicode_ci NOT NULL, `country` varchar(20) COLLATE utf8_unicode_ci NOT NULL, `created` datetime NOT NULL, `status` tinyint(1) NOT NULL DEFAULT 1 COMMENT '1=Active | 0=Inactive', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
Database Configuration (dbConfig.php):
The following code is used to connect the database using PHP and MySQL. Specify the database host ($dbHost
), username ($dbUsername
), password ($dbPassword
), and name ($dbName
) as per your database credentials.
<?php
// Database configuration
$dbHost = "localhost";
$dbUsername = "root";
$dbPassword = "root";
$dbName = "codexworld"; // Create database connection
$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName); // Check connection
if ($db->connect_error) {
die("Connection failed: " . $db->connect_error);
}
Export Data from Database:
The following code helps to export data from the MySQL database and download it as an excel file.
- The
filterData()
function is used to filter string before added to the excel data row. $fileName
– Define the name of the excel file to be downloaded.$fields
– Define the column named of the excel sheet.$excelData
– Add the first row to the excel sheet as a column name.- Fetch member’s data from the database and add to the row of the excel sheet.
- Define headers to force the file to download.
- Render data of excel sheet.
<?php
// Load the database configuration file
include_once 'dbConfig.php'; // Filter the excel data
function filterData(&$str){
$str = preg_replace("/t/", "\t", $str);
$str = preg_replace("/r?n/", "\n", $str);
if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
} // Excel file name for download
$fileName = "members-data_" . date('Y-m-d') . ".xls"; // Column names
$fields = array('ID', 'FIRST NAME', 'LAST NAME', 'EMAIL', 'GENDER', 'COUNTRY', 'CREATED', 'STATUS'); // Display column names as first row
$excelData = implode("t", array_values($fields)) . "n"; // Fetch records from database
$query = $db->query("SELECT * FROM members ORDER BY id ASC");
if($query->num_rows > 0){
// Output each row of the data
while($row = $query->fetch_assoc()){
$status = ($row['status'] == 1)?'Active':'Inactive';
$lineData = array($row['id'], $row['first_name'], $row['last_name'], $row['email'], $row['gender'], $row['country'], $row['created'], $status);
array_walk($lineData, 'filterData');
$excelData .= implode("t", array_values($lineData)) . "n";
}
}else{
$excelData .= 'No records found...'. "n";
} // Headers for download
header("Content-Type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename="$fileName""); // Render excel data
echo $excelData;exit;
Export HTML Table Data to Excel using JavaScript
Conclusion
If you want to add an export option to the data list, the export to excel feature is perfect for it. With the export option, the user can download the data in an excel file and save it in a local drive. You can use this simple code to add export data functionality in the web application using PHP.
- Excel
- Export
- MySQL
- PHP
Are you want to get implementation help, or modify or enhance the functionality of this script? Click Here to Submit Service Request
If you have any questions about this script, submit it to our QA community — Ask Question
After putting so much effort into importing your data into an SQL
database and connecting it to your website, how do you get it back out
and into Excel in order to keep your off-line and on-line systems
synchronised?
The following article presents a simple method for downloading any
data from PHP into an Excel spreadsheet — or at least something that
looks like one.
What we’re actually doing here is creating a
text (TAB or CSV) file containing the data which can then be opened by
Excel or any other spreadsheet. Before you ask, that means NO
formatting, NO colours and NO formulae — just the actual data.
For maximum compatibility with recent version of Excel, Numbers and
other applications you should use the CSV
download format rather than tab-delimted text.
Preparing the data
The following examples use the dataset created for and earlier
article Sorting Arrays of Arrays which is
defined as follows:
<?PHP
$data = [
["firstname" => "Mary", "lastname" => "Johnson", "age" => 25],
["firstname" => "Amanda", "lastname" => "Miller", "age" => 18],
["firstname" => "James", "lastname" => "Brown", "age" => 31],
["firstname" => "Patricia", "lastname" => "Williams", "age" => 7],
["firstname" => "Michael", "lastname" => "Davis", "age" => 43],
["firstname" => "Sarah", "lastname" => "Miller", "age" => 24],
["firstname" => "Patrick", "lastname" => "Miller", "age" => 27]
];
?>
Further down this page you will find examples for creating a
downloadable file using data sourced from an SQL query.
The first step is to output the data in a tab-delimited format (CSV
can also be used but is slightly more complicated). To achieve this we
use the following code:
<?PHP
header("Content-Type: text/plain");
$flag = FALSE;
foreach($data as $row) {
if(!$flag) {
// display field/column names as first row
echo implode("t", array_keys($row)) . "rn";
$flag = TRUE;
}
echo implode("t", array_values($row)) . "rn";
}
exit;
We set the content type to text/plain so that the output can
more easily be viewed in the browser. Otherwise, because there is no
HTML formatting, the output would appear as a single line of text.
The first line of output will be the column headings (in this case
the field names are used). Values are separated with a tab t
and rows with a line break n. The output should look
something like the following:
firstname lastname age
Mary Johnson 25
Amanda Miller 18
James Brown 31
Patricia Williams 7
Michael Davis 43
Sarah Miller 24
Patrick Miller 27
There’s already a weakness in this code that may not be immediately
obvious. What if one of the fields to be ouput already contains one or
more tab characters, or worse, a newline? That’s going to throw the
whole process out as we rely on those characters to indicate column- and
line-breaks.
The solution is to ‘escape’ the tab characters. In this case we’re
going to replace tabs with a literal t and line breaks with a
literal n so they don’t affect the formatting:
<?PHP
function cleanData(&$str)
{
$str = preg_replace("/t/", "\t", $str);
$str = preg_replace("/r?n/", "\n", $str);
}
header("Content-Type: text/plain");
$flag = FALSE;
foreach($data as $row) {
array_walk($row, __NAMESPACE__ . 'cleanData');
if(!$flag) {
// display field/column names as first row
echo implode("t", array_keys($row)) . "rn";
$flag = TRUE;
}
echo implode("t", array_values($row)) . "rn";
}
exit;
The __NAMESPACE__ reference and are required
to be compatible with PHP
Namespaces, and should be included whether or not you are currently
using namespaces for your code to be future-compatible.
Before each row is echoed any tab characters are replaced
«t» so that our columns aren’t broken up. Also any line
breaks within the data are replaced with «n». Now, how to
set this up as a download…
Triggering a download
What many programmers don’t realise is that you don’t have to create
a file, even a temporary one, in order for one to be downloaded. It’s
sufficient to ‘mimic’ a download by passing the equivalent HTTP headers
followed by the data.
If we create a PHP file with the following code then when it’s called
a file will be downloaded which can be opened directly using Excel.
<?PHP
function cleanData(&$str)
{
$str = preg_replace("/t/", "\t", $str);
$str = preg_replace("/r?n/", "\n", $str);
if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
}
// filename for download
$filename = "website_data_" . date('Ymd') . ".xls";
header("Content-Disposition: attachment; filename="$filename"");
header("Content-Type: application/vnd.ms-excel");
$flag = FALSE;
foreach($data as $row) {
array_walk($row, __NAMESPACE__ . 'cleanData');
if(!$flag) {
// display field/column names as first row
echo implode("t", array_keys($row)) . "rn";
$flag = TRUE;
}
echo implode("t", array_values($row)) . "rn";
}
exit;
Note that we’ve added an extra line to the cleanData
function to detect double-quotes and escape any value that contains
them. Without this an uneven number of quotes in a string can confuse
Excel.
source
This should result in a file being downloaded and saved to your
computer. If all goes well then the filename will be
named «website_data_20230414.xls» and will open in Excel looking something like this:
How does it work? Setting the headers tells the browser to expect a
file with a given name and type. The data is then echoed, but instead
of appearing on the page it becomes the downloaded file.
Because of the .xls extension and the vnd.ms-excel file
type, most computers will associate it with Excel and double-clicking
will cause that program to open. You could also modify the file name
and mime type to indicate a different spreadsheet package or database
application.
There is no way to specify data/cell formatting, column widths,
etc, using this method. To include formatting try generating HTML code
or a script that actually builds an Excel file. Or create your own
macro in Excel that applies formatting after the import.
A similar technique can be used to allow users to download files that
have been uploaded previously using PHP and stored with different names.
More on that later…
Exporting from an SQL database
If your goal is to allow data to be exported from a query result
then the changes are relatively simple:
<?PHP
// Original PHP code by Chirp Internet: www.chirpinternet.eu
// Please acknowledge use of this code by including this header.
function cleanData(&$str)
{
$str = preg_replace("/t/", "\t", $str);
$str = preg_replace("/r?n/", "\n", $str);
if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
}
// filename for download
$filename = "website_data_" . date('Ymd') . ".xls";
header("Content-Disposition: attachment; filename="$filename"");
header("Content-Type: application/vnd.ms-excel");
$flag = FALSE;
$result = pg_query("SELECT * FROM table ORDER BY field") or die('Query failed!');
while(FALSE !== ($row = pg_fetch_assoc($result))) {
array_walk($row, __NAMESPACE__ . 'cleanData');
if(!$flag) {
// display field/column names as first row
echo implode("t", array_keys($row)) . "rn";
$flag = TRUE;
}
echo implode("t", array_values($row)) . "rn";
}
exit;
This is the entire script required to query the database, clean the
data, and trigger a file download.
The database functions need to match the database you’re using.
MySQL users for example will need to use mysqli_query
and either mysqli_fetch_assoc or mysqli_fetch_assoc in place of the PostgreSQL
functions. Or better, PDO::query().
For other databases see under User Comments
below or check the PHP documentation.
If you are seeing duplicate
columns (numbered as well as labeled) you need to change the fetch call
to return only the associative (ASSOC) array.
If you’re having trouble at this stage, remove the
Content-Disposition header and change the Content-Type back to
text/plain. This makes debugging a lot easier as you can see
the output in your browser rather than having to download and open the
generated file every time you edit the script.
Preventing Excel’s ridiculous auto-format
When importing from a text file as we’re essentially doing here,
Excel has a nasty habit of mangling dates, timestamps, phone numbers and
similar input values.
For our purposes, some simple additions to the cleanData
function take care of most of the problems:
<?PHP
// Original PHP code by Chirp Internet: www.chirpinternet.eu
// Please acknowledge use of this code by including this header.
function cleanData(&$str)
{
// escape tab characters
$str = preg_replace("/t/", "\t", $str);
// escape new lines
$str = preg_replace("/r?n/", "\n", $str);
// convert 't' and 'f' to boolean values
if($str == 't') $str = 'TRUE';
if($str == 'f') $str = 'FALSE';
// force certain number/date formats to be imported as strings
if(preg_match("/^0/", $str) || preg_match("/^+?d{8,}$/", $str) || preg_match("/^d{4}.d{1,2}.d{1,2}/", $str)) {
$str = "'$str";
}
// escape fields that include double quotes
if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
}
?>
The section that prevents values being scrambled does so by inserting
an apostrophe at the start of the cell. When you open the resuling file
in Excel you may see the apostrophe, but editing the field will make it
disappear while retaining the string format. Excel is strange that way.
The types of values being escape this way are: values starting with a
zero; values starting with an optional + and at least 8
consecutive digits (phone numbers); and values starting with numbers in
YYYY-MM-DD format (timestamps). The relevant regular expressions have
been highlighted in the code above.
Exporting to CSV format
As newer versions of Excel are becoming fussy about opening files
with a .xls extension that are not actual Excel binary files, making CSV
format with a .csv extension is now a better option.
The tab-delimited text options describe above may be a bit limiting
if your data contains newlines or tab breaks that you want to preserve
when opened in Excel or another spreadsheet application.
A better format then is comma-separated variables (CSV) which can be
generated as follows:
<?PHP
// Original PHP code by Chirp Internet: www.chirpinternet.eu
// Please acknowledge use of this code by including this header.
function cleanData(&$str)
{
if($str == 't') $str = 'TRUE';
if($str == 'f') $str = 'FALSE';
if(preg_match("/^0/", $str) || preg_match("/^+?d{8,}$/", $str) || preg_match("/^d{4}.d{1,2}.d{1,2}/", $str)) {
$str = "'$str";
}
if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
}
// filename for download
$filename = "website_data_" . date('Ymd') . ".csv";
header("Content-Disposition: attachment; filename="$filename"");
header("Content-Type: text/csv");
$out = fopen("php://output", 'w');
$flag = FALSE;
$result = pg_query("SELECT * FROM table ORDER BY field") or die('Query failed!');
while(FALSE !== ($row = pg_fetch_assoc($result))) {
array_walk($row, __NAMESPACE__ . 'cleanData');
if(!$flag) {
// display field/column names as first row
fputcsv($out, array_keys($row), ',', '"');
$flag = TRUE;
}
fputcsv($out, array_values($row), ',', '"');
}
fclose($out);
exit;
Normally the fputcsv command is used to write data in CSV
format to a separate file. In this script we’re tricking it into
writing directly to the page by telling it to write to
php://output instead of a regular file. A nice trick.
source
As an aside, to export directly to CSV format from the command line
interface in PostgreSQL you can use simply:
postgres=# COPY (SELECT * FROM table ORDER BY field) TO '/tmp/table.csv' WITH CSV HEADER;
and for MySQL, something like the following:
SELECT * FROM table ORDER BY field
INTO OUTFILE '/tmp/table.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY 'n'
Exporting to CSV with Unicode intact
If like us your data contains UTF-8 characters you will notice that
Excel doesn’t handle them very well. Other applications can open UTF-8
content without problems, but Microsoft apparently still occupies the
dark ages.
Fortunately, there is a trick you can use. Below you can see how we
modify the script to convert everything from UTF-8 to UTF-16 Lower
Endian (UTF-16LE) format which Excel, at least on Windows, will recognise.
When opening this file in Excel you might find all the data
bunched into the first column. This should be fixable using the
«Text to Columns…» command under the Data menu.
<?PHP
// Original PHP code by Chirp Internet: www.chirpinternet.eu
// Please acknowledge use of this code by including this header.
function cleanData(&$str)
{
if($str == 't') $str = 'TRUE';
if($str == 'f') $str = 'FALSE';
if(preg_match("/^0/", $str) || preg_match("/^+?d{8,}$/", $str) || preg_match("/^d{4}.d{1,2}.d{1,2}/", $str)) {
$str = "'$str";
}
if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
$str = mb_convert_encoding($str, 'UTF-16LE', 'UTF-8');
}
// filename for download
$filename = "website_data_" . date('Ymd') . ".csv";
header("Content-Disposition: attachment; filename="$filename"");
header("Content-Type: text/csv; charset=UTF-16LE");
$out = fopen("php://output", 'w');
$flag = FALSE;
$result = pg_query("SELECT * FROM table ORDER BY field") or die('Query failed!');
while(FALSE !== ($row = pg_fetch_assoc($result))) {
array_walk($row, __NAMESPACE__ . 'cleanData');
if(!$flag) {
// display field/column names as first row
fputcsv($out, array_keys($row), ',', '"');
$flag = TRUE;
}
fputcsv($out, array_values($row), ',', '"');
}
fclose($out);
exit;
This script may not work for all versions of Excel. Please let us
know using the Feedback form below if you encounter problems or come up
with a better solution.
Changing column headings
The above database download examples all use the database field
names for the first row of the exported file which may not be what you
want. If you want to specify your own more user-friendly headings you
can modify the code as follow:
<PHP
$colnames = [
'memberno' => "Member No.",
'date_joined' => "Date joined",
'title' => "Title",
'firstname' => "First name",
'lastname' => "Last name",
'address' => "Address",
'postcode' => "Postcode",
'city' => "City",
'country' => "Country",
'phone' => "Telephone",
'mobile' => "Mobile",
'fax' => "Facsimile",
'email' => "Email address",
'notes' => "Notes"
];
function map_colnames($input)
{
global $colnames;
return isset($colnames[$input]) ? $colnames[$input] : $input;
}
// filename for download
$filename = "website_data_" . date('Ymd') . ".csv";
...
if(!$flag) {
// display field/column names as first row
$firstline = array_map(__NAMESPACE__ . 'map_colnames', array_keys($row));
fputcsv($out, $firstline, ',', '"');
$flag = TRUE;
}
...
?>
The values in the first row will be mapped according to the
$colnames associative array. If no mapping is provided for a
fieldname it will remain unchanged. Of course you will want to provide
your own list of suitable headings. They don’t have to be in order.
source
References
- Easy way to create XLS file from PHP
- Keeping leading zeros and large numbers
< PHP
Most recent 20 of 63 comments:
Post your comment or question
xls_export_php
Экспорт таблицы HTML в Excel
Экспорт таблицы в Excel при помощи PHP
У многих возникает проблема с экспортом простых HTML таблиц в Excel (*.xls). Сегодня мы покажем, как это можно сделать простым способом, не применяя дополнительных библиотек, используя PHP
Допустим у нас имеется любая HTML таблица (table).
Необходимо выгрузить её в Excel при нажатии кнопки.
Вот решение:
Добавим кнопку «сформировать Excel»:
<form action="xls.php" method="POST"> <input type="hidden" name="data" id="xls_data" value=""> <input type="hidden" name="report_name" value="x_report"> <input type="submit" value="Excel" class="r_report_button--excel" disabled> </form>
xls_data — Данные, которые передаем, в данном случае таблица.
report_name — Имя отчета
r_report_button — Сабмит. Кнопка отправки.
Теперь скрипт (jQuery), который поможет отправить таблицу POST-запросом:
$(document).ready(function() { $('.r_report_button--excel').attr('disabled', false); var excel_data = $('#x_report_table').html(); var report_data = $('.report_table').html(); $('#xls_data').val(excel_data); $('#report_data').val(report_data); });
Активируем кнопку, как страница прогрузится до конца (нужно, если реально огромный объем данных).
Hidden поля заполняются данными из таблицы. При нажатии кнопки запрос отправляется в файл xls.php
header('Content-Type: application/vnd.ms-excel; charset=utf-8;'); header('Content-disposition: attachment; filename='.$_POST["report_name"].'_'.date("d-m-Y").'.xls'); header("Content-Transfer-Encoding: binary "); echo ' <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <meta name="author" content="Sadovikow" /> <title>Demo</title> </head> <body>'; echo '<table border="1" cellpadding="15">'; echo $_POST["data"]; echo '</table>'; echo '<br>'; echo '</body></html>';
В данном коде реализована формирование таблицы при помощи HTML. Заголовки нужны для корректной кодировки, очень важно, если имеется кириллица.
Всё очень просто, абсолютно любая таблица может спокойно быть экспортирована в Excel!