HTML Table to Ms Excel Using PHP and jQuery - php

I am trying to export an HTML existing table to MS Excel with assigned Name. As you know exporting HTML Table to Excel file can be achieved by jQuery BUT as I said I have to add a Name to File as well.
HTML
<button id="myButtonControlID">Export Table to Excel</button>
<div id="divTableDataHolder">
<title>Demo for huge data</title>
<table>
<tbody>
<tr>
<td>abc</td>
<td>12</td>
</tr>
<tr>
<td>abc</td>
<td>12</td>
</tr>
</tbody>
</table>
</div>
So Far I have a jquery which pass data from html to PHP file as:
$( document ).ready(function() {
var naem = "MyExcel";
$("[id$=myButtonControlID]").click(function (e) {
window.open('getMyXSL.php?data=' + encodeURIComponent($('div[id$=divTableDataHolder]').html())+'&name='+name);
e.preventDefault();
});
});
and in getMyXSL.php file I have
<?php
header('Content-Disposition: attachment; filename="'.$_REQUEST['name'].'"');
header('Content-Type: application/vnd.ms-excel');
echo($_REQUEST['data']);
?>
but when I the buton clicked file generates/download a PHP file called getMyXSL.php which looks like this
<title>Demo for huge data</title>
<table>
<tbody>
<tr>
<td>abc</td>
<td>12</td>
</tr>
<tr>
<td>abc</td>
<td>12</td>
</tr>
</tbody>
</table>
Can you please let me know how to fix this and how I can export the table to .xls with a name? Thanks

Extension of output file must be xls, but your script is not generates this correctly. For fix it, you need to change header information:
<?php
$filename = sprintf('%s.xls', rawurlencode(preg_replace('~&#(\d{3,8});~e', '$fixchar(\'$1\')', $_REQUEST['name'])));
header('Content-Disposition: attachment; filename="'.$filename.'";' );
header('Content-Type: application/vnd.ms-excel');
echo($_REQUEST['data']);
?>

<table border="1" id="ReportTable" class="myClass">
<tr bgcolor="#CCC">
<td width="100">Fecha</td>
<td width="700">Seguimiento</td>
<td width="170">Producto</td>
<td width="30"> </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" nClick="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">
In the onSubmit event of form, I am appending the div with ReportTable table. Using clone() method of jquery, I am making the clone of the ReportTable table that I wanted to export to excel, and in the end I am assigning the html of that cloned table to hidden field available in my form so that when form is posted then the data will be transferred to the exporttoexcel.php web page and in that web page I have all my logic for exporting data to excel in php.
Note: - For this example to run properly, there must be no declaration of inline css in your table or div that you want to export. Whenever you use the style attribute to give inline css, the export to excel functionality will not be performed according to your expectations.
exporttoexcel.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'];
?>

var naem = "MyExcel";
It should be name, that is the error.

Related

How to exclude HTML from PHP and PHP file still able to link with the HTML file?

View table<-- this is my example. And code is provided too. I need to separate HTML from PHP, moving HTML to another file but my PHP code still be able to link with it. Is there any idea? I am trying to make something like View model controller.
<html>
<head>
<meta charset="utf-8">
<title>View Records</title>
<link rel="stylesheet" href="css/style.css" />
</head>
<body>
<div class="form">
<p>
Dashboard
| View Records
| Add Admin
| Logout
</p>
<table width="100%" border="1" style="border-collapse:collapse;">
<thead>
<tr>
<th><strong>ID</strong></th>
<th><strong>Username</strong></th>
<th><strong>User Password</strong></th>
<th><strong>Full Name</strong></th>
<th><strong>Edit</strong></th>
<th><strong>Delete</strong></th>
</tr>
</thead>
</body>
<?php
$count=1;
$sel_query="Select * from admin ORDER BY id ASC;";
$result = mysqli_query($con,$sel_query);
while($row = mysqli_fetch_assoc($result)) { ?>
<tr>
<td align="center"><?php echo $row["ID"]; ?></td>
<td align="center"><?php echo $row["username"]; ?></td>
<td align="center"><?php echo $row["user_pass"]; ?></td>
<td align="center"><?php echo $row["fullname"]; ?></td>
<td align="center">
Edit</td>
<td align="center">
Delete</td>
</tr>
<?php $count++; } ?>
</tbody>
</table>
</div>
</body>
</html>```
Separating the php and html is a good start, and helps you see the next step in converting to OOP and then MVC.
MVC at this point is too broad for a simple answer here, but I would recommend this as a first step as it has the underlying principles:
PHP is always at the top; never output anything until all your logic is finished
Load configuration
Work with user input and redirect if POST
Execute business logic
Exit PHP and output HTML. Remember, PHP is essentially a templating language, might as well use it as such
Your code would then look something like this:
<?php
// load database connection, etc
$url = 'your url';
// deal with user input. Always use POST if data will be changed!
if($_POST['action'] == 'delete') {
// delete from admin where id=?
header('location: '.$url);
die;
}
// end "controller" section
// begin "model" section
$sel_query="Select * from admin ORDER BY id ASC;";
$result = mysqli_query($con,$sel_query);
// end "model" section
// begin "view" section.
// Note, you could simply put the html in a separate file and just include it here.
?>
<html>
<head>
<meta charset="utf-8">
<title>View Records</title>
<link rel="stylesheet" href="css/style.css" />
</head>
<body>
<div class="form">
<p>
Dashboard
| View Records
| Add Admin
| Logout
</p>
<table width="100%" border="1" style="border-collapse:collapse;">
<thead>
<tr>
<th><strong>ID</strong></th>
<th><strong>Username</strong></th>
<th><strong>User Password</strong></th>
<th><strong>Full Name</strong></th>
<th><strong>Edit</strong></th>
<th><strong>Delete</strong></th>
</tr>
</thead>
</tbody>
<?php while($row = mysqli_fetch_assoc($result)): ?>
<tr>
<td align="center"><?= $row["ID"] ?></td>
<td align="center"><?= $row["username"] ?></td>
<td align="center"><?= $row["user_pass"] ?></td>
<td align="center"><?= $row["fullname"] ?></td>
<td align="center">
<form method="post">
<input type="hidden" name="action" value="delete" />
<input type="hidden" name="id" value="<?= $row["ID"] ?>" />
<input type="submit" value="Delete" />
</form>
</td>
</tr>
<?php endwhile; ?>
</tbody>
</table>
</div>
</body>
</html>
Notice that following this pattern is laying the groundwork for moving to mvc. But first, start working on your oop chops and move all the business logic into a model object.
After that, you can move the template to its own file, and have the model injected into the view, which lets the view have access to the info it needs, and then render the output.
Meanwhile, you'll need a router (all traffic is rerouted to index.php) and controller, and figure out which interpretation of MVC you will use ;)
Here's a very basic solution.
Make an HTML file as a template. E.g. "template.html". Use HTML comments as placeholders for the data. (I went with comments as it means the HTML remains compliant)
I've left out some of the non-relevant bits, so hopefully you get the idea:
<html>
...
<table width="100%" border="1" style="border-collapse:collapse;">
<thead>
<tr>
<th><strong>ID</strong></th>
<th><strong>Username</strong></th>
<th><strong>User Password</strong></th>
<th><strong>Full Name</strong></th>
<th><strong>Edit</strong></th>
<th><strong>Delete</strong></th>
</tr>
</thead>
<tbody>
<!--ROW-->
<tr>
<td align="center"><!--ID--></td>
<td align="center"><!--username--></td>
<td align="center"><!--user_pass--></td>
<td align="center"><!--fullname--></td>
<td align="center">
Edit</td>
<td align="center">
Delete</td>
</tr>
<!--ENDROW-->
</tbody>
</table>
</div>
</body>
</html>
Then, in your PHP code, you read in the html, find the row template, and replace the fields as needed:
<?php
// Read the template
$html = file_get_contents('template.html');
// Find the row template
$regRowTemplate = '/<!--ROW-->(.*)<!--ENDROW-->/i';
preg_match($regRowTemplate, $html, $m);
$rowTemplate = $m[1];
// Start building our replacement rows
$htmlRows = '';
$count=1;
$sel_query="Select * from admin ORDER BY id ASC;";
$result = mysqli_query($con,$sel_query);
while ($row = mysqli_fetch_assoc($result)) {
// Start with a fresh copy of the template
$htmlRow = $rowTemplate;
// Replace comment placeholders with values
foreach ($row as $key => $value) {
$htmlRow .= str_replace('<!--' . $key . '-->', $value, $htmlRow);
}
// Append to our rows
$htmlRows .= $htmlRow;
$count++;
}
// Replace the row template with our expanded rows
$html = preg_replace(regRowTemplate, $htmlRows, $html);
// Do something with the html
Source untested, but should give you a good starting point. I kept it pretty raw. If I was doing this for real, I'd allow for the possibility of spaces in the comment placeholders by using a regular expression instead, but for now it's good enough.

export images with data from Mysql to excel using php

Am trying to export my data along side images from mysql database using php.
The plain data is successfully exported to excel but the images donot display rather display error "the linked image cannot be displayed.The file may have been moved,renamed or deleted.Verify link points to correct file and location".
Output of the code
source code
<?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=system_users.xls");
// Add data table
include("config/dbconfig.php");
?>
<!-- Image path in subfolder images -->
<img src="images/reph.png" height="115" width="730">
<table width=70% border="1" class="view" align="center">
<tr><th> No</th>
<th> Name</th>
<th>User Role</th>
<th>User Name</th>
<th>Password</th>
</class> </tr><tr>
<?php
$sno=1;
$query=mysql_query("select * from users ");
$num_rows=mysql_num_rows($query);
if($num_rows>0)
{ while ($fields=mysql_fetch_assoc($query))
{ $sno<=$num_rows;
$pid=$fields['user_id'];
$lname=$fields['lname'];
?>
<td> <?php echo "$sno ";
$sno++; ?></td>
<td> <?php echo $fields['lname']." ".$fields['fname'];?></td>
<td><?php // php code that retrieves image path from the database and prints the image
//echo '<img width="120" height="110" SRC="' .$fields['image'] . '" alt="Image failed to load " />';
?></td>
<td> <?php echo $fields['role'];?></td>
<td> <?php echo $fields['username'];?></td>
<td> <?php echo $fields['password'];?></td>
</tr>
<?php
}//closing the while loop
}//closing the if statement
echo '</table>';
?>

FPDF html table to display data from mysql

I'm new to fpdf and I'm having trouble on how can I display the data based on my input field. In myh input field php file I will put the name,date etc and I have a print button where when I clicked It will automatically print what I inputted in that field. Now I want that to be printed in a table form format. Below is the fpdf file:
<?php
$html = <<<MYTABLE
<table border="1" style="width:90%" title="Leave" cellpadding="5px" align="center">
<tr>
<td rowspan=1 width="70" align:"top-left"><center><b>1. Name:</b></center><br><select name="office_agency"></td>
<td rowspan=1 width="100" colspan="2" align:"top-left"><b>2. ID / Date</b><br> </td>
</tr>
<tr>
......
</tr>
</table>
MYTABLE;
require('pdftable.inc.php');
mysql_connect('localhost','root','');
mysql_select_db('auth');
$p = new PDFTable();
$p->AddPage();
$p->setfont('times','',10);
$p->Cell(5,-5,'APPLICATION FOR LEAVE');
$p->Ln(3);
$p->htmltable($html);
$p->output();
?>
There. how can put the code for fetching the inputted data following the html format or is there any way than this? thanks
Here you cannot use the html table for direct display,you can create the table using the col() syntax for more check this link [here]
http://www.fpdf.org/en/script/script14.php

Export to excel with multiple sheet using codeigniter?

I have a table which contain employee details.I have to export these employee details in excel sheet.In excel each sheet contain each employee details and sheet name should be employee name. In models I have writen a query to fetch the details from database the following is the sample view code. This following code will give only one sheet of result How I implement multiple sheet excel
<?PHP
header ("Cache-Control: no-cache, must-revalidate");
header ("Pragma: no-cache");
header ('Content-type: application/x-msexcel');
header ("Content-Disposition: attachment; filename=employee_workbook.xls" );
$this->load->view('reader/reader');
?>
<?PHP
if($result->num_rows()>0)
{
?>
<?PHP foreach($result->result_array() as $entry):?>
<table width="100%" border="1" cellpadding="1" cellspacing="1" bgcolor="#FFFFFF">
<tr>
<td width="200" bgcolor="#FFFFFF"><strong>Employee ID</strong></td>
<td width="150" bgcolor="#FFFFFF"><strong>Employee Name</strong></td>
<td width="150" bgcolor="#FFFFFF"><strong>Check in Time</strong></td>
<td width="100" bgcolor="#FFFFFF"><strong>Project Name</strong></td>
<td width="100" bgcolor="#FFFFFF"><strong>Check Out Time</strong></td>
</tr>
<tr>
<td align="left" bgcolor="#FFFFFF"><?php echo $entry['emp_id']; ?></td>
<td align="left" bgcolor="#FFFFFF"><?PHP echo $entry['emp_name']; ?></td>
<td align="left" bgcolor="#FFFFFF"><?PHP echo $entry['in_time']; ?></td>
<td align="left" bgcolor="#FFFFFF"><?PHP echo $entry['prj_name']; ?></td>
<td align="left" bgcolor="#FFFFFF"><?PHP echo $entry['out_time']; ?></td>
</tr>
</table>
<?PHP endforeach;?>
<?PHP
}
?>
You might want to look into PHPExcel, I have tried almost every script out there to export data to excel, nothing does it better than PHPExcel, you can even export to multiple sheets.
You can also use EasyXLS. Download the Excel library for PHP.
You can find a lot a code samples starting from here. You can save multiple sheets using this library.

How to display filled information of appended row in another page? [duplicate]

This question already has answers here:
why the appended row's data didn't displayed after being submitted?
(2 answers)
Closed 9 years ago.
This page got a button ADD to append the row.Once the appended row is filled,when submit,it will connect/link to another page ,then the filled information will display at that page.But the problem is how to display the filled information of appended row on 2nd page had been done in 1st page by using PHP.(Sorry for my poor English and hope for understand).
<table width="600px" id="project">
<tr>
<td>1</td>
<td><textarea name="pro_1" cols="100" rows="2"></textarea></td>
</tr>
<tr>
<td>2</td>
<td><textarea name="pro_2" cols="100" rows="2"></textarea></td>
</tr>
<tr>
<td>3</td>
<td><textarea name="pro_3" cols="100" rows="2"></textarea></td>
</tr>
</table>
<input id="addbtn" type="button" name="addbtn" value="ADD">
Jquery script(for append the row):
$(document).ready(function() {
$("#addbtn").click(function(){
var num=parseInt($("#project tr:last").text());
num+=1;
$("#project").append("<tr><td>"+num+"</td><td><textarea cols='100' rows='2'></textarea></td></tr>");
});
PHP source code(for 2nd page):
<table width="600px" id="pub">
<tr>
<td>1</td>
<td><?php echo $_post["pro_1"]; ?></td>
</tr>
<tr>
<td>2</td>
<td><?php echo $_post["pro_2"]; ?></td>
</tr>
<tr>
<td>3</td>
<td><?php echo $_post["pro_3"]; ?></td>
</tr>
</table>
Give the dynamically-added textarea a name, then you following page will see it as a parameter & can render it back out in the HTML.
In the Javascript: (PLEASE don't try and munge all your code, on one line!):
$("#project").append("<tr>);
$("#project").append("<td>"+num);
$("#project").append("<td><textarea name='pro_"+num+"' cols='100' rows='2'></textarea>");
See how a pinch of readability, makes it comprehensible? I'm following the HTML spec that says </td> and </tr> are OPTIONAL, not mandatory -- I never emit them myself.
And in your PHP second page, you need to pick up the correct parameter name. (You're looking for pub_N, not pro_N which you appear to post under).
Tidy your code up, get your names right.
Then put a PHP loop around it, to render Project Names with ascending numbers until it runs out of parameters. My PHP code is rough, but..
<?php
$rowNum = 1;
while (true) {
$rowValue = $_post["pro_"+$rowNum];
if (! isset($rowValue))
break; // Reached the end.
?>
<tr>
<td><?= htmlentities( $rowValue) ?></td>
<?php
}
?>
Hope this helps!

Categories