How to export html table to excel or pdf in php
Use a PHP Excel for generatingExcel file. You can find a good one called PHPExcel here: https://github.com/PHPOffice/PHPExcel
And for PDF
generation use http://princexml.com/
How to Export Html Table to CSV and PDF with formatting using Php
Download CSV from HTML from end
$(function () { $(".export-csv").on('click', function (event) { // CSV var filename = $(".export-csv").data("filename") var args = [$('#fixed_table'), filename + ".csv", 0]; exportTableToCSV.apply(this, args); }); $(".export-txt").on('click', function (event) { // txt var filename = $(".export-txt").data("filename") var args = [$('#fixed_table'), filename + ".txt", 0]; exportTableToCSV.apply(this, args); });
function exportTableToCSV($table, filename, type) { var startQuote = type == 0 ? '"' : ''; var $rows = $table.find('tr').not(".no-csv"), // Temporary delimiter characters unlikely to be typed by keyboard // This is to avoid accidentally splitting the actual contents tmpColDelim = String.fromCharCode(11), // vertical tab character tmpRowDelim = String.fromCharCode(0), // null character // actual delimiter characters for CSV/Txt format colDelim = type == 0 ? '","' : '\t', rowDelim = type == 0 ? '"\r\n"' : '\r\n', // Grab text from table into CSV/txt formatted string csv = startQuote + $rows.map(function (i, row) { var $row = $(row), $cols = $row.find('td,th'); return $cols.map(function (j, col) { var $col = $(col), text = $col.text().trim().indexOf("is in cohort") > 0 ? $(this).attr('title') : $col.text().trim(); return text.replace(/"/g, '""'); // escape double quotes
}).get().join(tmpColDelim);
}).get().join(tmpRowDelim) .split(tmpRowDelim).join(rowDelim) .split(tmpColDelim).join(colDelim) + startQuote; // Deliberate 'false', see comment below if (false && window.navigator.msSaveBlob) { var blob = new Blob([decodeURIComponent(csv)], { type: 'text/csv;charset=utf8' });
window.navigator.msSaveBlob(blob, filename);
} else if (window.Blob && window.URL) { // HTML5 Blob var blob = new Blob([csv], { type: 'text/csv;charset=utf8' }); var csvUrl = URL.createObjectURL(blob);
$(this) .attr({ 'download': filename, 'href': csvUrl }); } else { // Data URI var csvData = 'data:application/csv;charset=utf-8,' + encodeURIComponent(csv);
$(this) .attr({ 'download': filename, 'href': csvData, 'target': '_blank' }); } }
});
<html><head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Export CSV</title><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <style type="text/css"> #page-wrapper { margin: 0 0 0 0; } </style></head><body> <div id="wrapper"> <!-- Page Content --> <div id="page-wrapper"> <div class="container-fluid"> <div class="row"> <div class="col-lg-12">
<style>
</style><h2> Export to CSV
<!-- Single button --> <span class="btn-group pull-right"> <ul class="dropdown-menu"> <li><a href=javascript:; class="export-csv" data-filename="CSVFILE">CSV</a></li> <li><a href=javascript:; class="export-txt" data-filename="TXTFILE">Flat file</a></li> </ul> </span>
</h2><hr />
<div class="row"> <div class="col-md-2 col-sm-4 col-xs-12">
</div></div><div class="row"> <div class="col-md-12"> <div class="table-responsive"> <table id="fixed_table" class="table table-condensed row-border order-column" cellspacing="0"> <thead> <tr> <th>First Header</th> <th >Second Header</th>
</tr> </thead> <tbody> <tr> <td class="text-center"> First Row column 1</td> <td>First Row column 2</td> </tr> </tbody> </table> </div> </div></div>
</body></html>
Export html table to excel with Spanish characters
header("Content-Type: application/vnd.ms-excel; charset=utf-8");
header("Content-type: application/x-msexcel; charset=utf-8");
header("Pragma: no-cache");
header('Content-Encoding: UTF-8');
header ("Content-Disposition: attachment; filename=\"$file_name" );
header ("Content-Description: Generated Report" );
if (mb_detect_encoding($content) == 'UTF-8') {
$content = mb_convert_encoding($content , "HTML-ENTITIES", "UTF-8");
}
echo $content;
Export PHP table with pagination to EXCEL, PDF, PRINTABLE
@lawrence agulto I changed this code to procedural type as you said. Try this code.
Download In excel:
<?php
include_once "connect.php";
$query = mysqli_query($conn,"SELECT * FROM tblSales ORDER BY date DESC ");
$columnHeader = "Column Name"."\t"."Column Name1"."\t"."Column Name2"."\t"."Column Name3"."\t";
$setData='';
if (mysqli_num_rows($query) > 0) {
while ($rec = mysqli_fetch_assoc($query)) {
$rowData = '';
foreach ($rec as $value) {
$value = '"'.$value.'"'."\t";
$rowData.=$value;
}
$setData.=trim($rowData)."\n";
}
}
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=Nobelz_Sushank.xls");
header("Pragme: no-cache");
header("Expires: 0");
echo "\t\tSales Data\n";
echo ucwords($columnHeader)."\n".$setData."\n";
?>
Download in pdf :
Download the FPDF library from here.
And change the query, table name, and TABLE_COLUMN_NAME according to your need.
<?php
$result = mysqli_query($conn," Your QUery");
$header = mysqli_query($conn,"SELECT UCASE(`COLUMN_NAME`)
FROM `INFORMATION_SCHEMA`.`COLUMNS`
WHERE `TABLE_SCHEMA`='DB_NAME'
AND `TABLE_NAME`='TABLE_NAME'
and `COLUMN_NAME` in ('TABLE_COLUMN_NAME','TABLE_COLUMN_NAME1', 'TABLE_COLUMN_NAME2', 'TABLE_COLUMN_NAME3')");
require('fpdf181/fpdf.php');
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
foreach($header as $heading) {
foreach($heading as $column_heading)
$pdf->Cell(95,12,$column_heading,1);
}
foreach($result as $row) {
$pdf->Ln();
foreach($row as $column)
$pdf->Cell(95,12,$column,1);
}
$pdf->Output();
?>
Related Topics
Function Eregi() Is Deprecated
Org.JSON.JSONexception: Value <Br of Type Java.Lang.String Cannot Be Converted to JSONobject
Converting an Array from One to Multi-Dimensional Based on Parent Id Values
Using Sprockets as a Standalone Service for a PHP Application
Are PHP Associative Arrays Ordered
Automatically Detect User's Current Local Time with JavaScript or PHP
How to Count Same Values in an Array and Store It to a Variable
PHP - How to Parametrize SQL Query with Multiple Where Conditions (Prepared Statement)
PHP Foreach by Reference Causes Weird Glitch When Going Through Array of Objects
Calendar Using JavaScript/ PHP/ MySQL
How to Find Number of Mondays or Tuesdays Between Two Dates
How to Use Prepare() with Dynamic Column Names
Vim Inoremap for Specific Filetypes
MySQL Select Records Greater Than 3 Months