Export Table as Excel file in php - php

CSS is effecting in UI but not in Excel. Anyone can help me on this please.
Below code will export table into excel but not able to provide space before tags.
<?php
echo $excel_data = '<table border="1">
<thead>
<th align="left">S.No.</th>
<th align="left">Name</th>
<th align="left">DOJ</th>
</thead>
<tbody>
<tr>
<td align="left">1</td>
<td align="left">Sreekanth Kuriyala</td>
<td align="left">04-06-2015</td>
</tr>
<tr>
<td align="left">2</td>
<td style="padding-left:20px;">SK</td>
<td align="left">26-07-2015</td>
</tr>
</tbody>
</table>';
$excel_file = 'Reports.xls';
file_put_contents ($excel_file, $excel_data);
?>
</br>
</br>
<a href="<?php echo $excel_file; ?>" download>Export to Excel</a>

you have to create a CSV file just create new php file with a function that expects a result of a db select.
then just echo cols separated by ; and carrier return for next row.
this is a function i made:
<?php
function printcsv($result){
//result of database select
header('Content-Encoding: UTF-8');
header('Content-type: text/csv; charset=UTF-8');
header('Content-Disposition: attachment; filename=example.csv');
echo "\xEF\xBB\xBF";
$nl = "\n";
//this will be the carrier return var
if($rs = $result->fetch_array(MYSQLI_NUM)){
while($rs != ''){
echo $rs[0].";".$rs[1].";".$rs[2].";".$rs[3].";".$rs[4].";".$rs[5].";".$nl;
$rs = $result->fetch_array(MYSQLI_NUM);
}
}
}
?>
change my mysqli_fetch_array by your result desired fetch and try it =)
oh, and you cannot write tables on it, only echo data separated by semicolon. each data for each column, semicolon to put the next data in next column, and carrier return to write in next row.
cheers!

Related

How to fetch id of selected chebox and export selected record as CSV using Codeigniter()?

I am not able to get how I can fetch the ids to export the records.
I have a dropdown button which contains three options (import, export and create new user). Once I click on the export button, the records where the checkbox is selected should be exported as a CSV file.
How the button looks like:
I have code for exporting a CSV file, but I am not able to fetch the ids of the checkboxes.
Export CSV file code (working fine):
public function export_csv($param = '')
{
$filename = strtotime("now"). ".csv";
$delimiter = ",";
// Create a file pointer
$f = fopen('php://memory', 'w');
// Set column headers
$fields = array('Id', 'Name', 'Email', 'Phone', 'Created', 'Status');
fputcsv($f, $fields, $delimiter);
$lineData = array(1,'34',$param,'859685968','29-09-2019','online');
fputcsv($f, $lineData, $delimiter);
// Move back to beginning of file
fseek($f, 0);
ob_clean();
// Set headers to download file rather than displayed
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="' . $filename . '";');
// Output all remaining data on a file pointer
fpassthru($f);
// Exit from file
exit();
}
HTML table will be looking like:
<table class="table">
<thead>
<tr>
<th style="width: 2%;"><input type="checkbox" name="select_all" id="select_check" class="checkbox select_check" ></th>
<th style="width: 18%;">الاسم</th>
<th style="width: 5%;"></th>
<th style="width: 25%;">البريد الالكتروني</th>
<th style="width: 20%;">مدينة</th>
<th style="width: 20%;">اخر ظهور</th>
<th style="width: 50%;">زيارات الموقع</th>
</tr>
</thead>
<tbody>
<?php if (count($all_visitors) > 0): ?>
<?php foreach($all_visitors as $visitor) : ?>
<form method="POST">
<tr>
<td><input type="checkbox" name="select_checkbox[]" id="select_checkbox" class="checkbox selectall_checkbox" value="<?=$visitor['id']?>"></td>
<td><?= !empty($visitor['full_name']) ? $visitor['full_name'] : 'الاسم لم يعطى حتى الان'?></td>
<td><i class="fa fa-comments" aria-hidden="true"></i> </td>
<td><?= !empty($visitor['email']) ? $visitor['email'] : 'البريد الإلكتروني لم يعطى حتى الان'?></td>
<td><?= !empty($visitor['city']) ? $visitor['city'] : 'لم يتم إعطاء المدينة بعد'?></td>
<td><?= !empty($visitor['updated']) ? get_timeago(strtotime($visitor['updated'])) : '30 Seconds ago'?></td>
<td class="site-visits" ><?= !empty($visitor['total_visits']) ? $visitor['total_visits'] : '0'?></td>
</tr>
</form>
<?php endforeach; ?>
<?php else:?>
<tr><td colspan="6">No records found</td></tr>
<?php endif; ?>
</tbody>
</table>
Once you post data to your controller method,
access them like below
$ids=$this->input->post('select_checkbox');
If you do, print_r($ids), you will have values like below for example
Array ( [0] => 1 [1] => 2 )
Then, make create query and export to csv, codeigniter dbutil has easy way to transform your query to csv, below is snippet to do that,
public function export_csv()
{
/* Usually ids will be integers, so lets just filter only integer ids
from user input,
1st RULE : Never Trust User Inputs
2nd RULE : always validate User Inputs
*/
$ids = array_filter( $this->input->post('select_checkbox'), 'is_int');
if($ids)
{
$this->load->dbutil();
$this->load->helper('file');
$this->load->helper('download');
$query = $this->db->select('Id', 'Name', 'Email', 'Phone', 'Created', 'Status')
->where_in('Id', $ids)
->get("your_table");
$delimiter = ",";
$newline = "\r\n";
$data = $this->dbutil->csv_from_result($query, $delimiter, $newline);
/* output to browser */
force_download('Somereport.csv', $data);
}
}
if you prefer to download on click of somebutton, then your JQuery snippet would be,
$(function(){
/* Easy way is to set
action="http://example.com/your_controller/export_csv"
in your export form and then submit
*/
$('#your_export_button_outside_form').on("click",function()
{
/*
$('#your_export_form').attr('action','http://example.com/your_controller/export_csv');
*/
$('#your_export_form').submit();
});
})

Format cell file .xls made by php

I have a MySQL database where I have a table with several columns and records.
I have made a .php script can made a file .xls with all records can i have in my table.
Everything works fine but the problem occurs when i find an id like this '36E49'.Microsoft Excel format the cell that contains the value '36E49' in scientific and the value become '3,6E+50'.
Example of my code:
<?php
header("Content-type: application/vnd.ms-excel; name='excel'");
header("Content-Disposition: filename=$filename");
?>
<table width="1702" border="1" style="border-collapse: collapse;">
<tr>
<td style="background-color: #F0F0F0; text-align: center;" width="160"><b><u>ID</u></b></td>
<td style="background-color: #F0F0F0; text-align: center;" width="170"><b><u>Description</u></b></td>
</tr>
<?php
$query = mysql_query ("SELECT * FROM ..............");
while($result = mysql_fetch_array($query))
{
$id1 = $result['id1'];
$id2 = $result['id2'];
echo "<tr>";
echo "<td>$id1</td>";
echo "<td>$id2</td>";
echo "</tr>";
}
?>
</table>
Thanks!
I 've solved the problem
For solve my problem i had use the fuction ="value"
Example:
<?php
echo "<td>=\"$id1\"</td>";
?>
Or if you are not in php:
<td><?php echo "=\"$id\""; ?></td>
I 've solved the problem
For solve my problem i had use the fuction ="value"
Example:
<?php
echo "<td>=\"$id1\"</td>";
?>
Or if you are not in php:
<td><?php echo "=\"$id\""; ?></td>

create horizontal bar chart

I want to make a horizontal bar chart in a web-page using php,mysql,javascript,css,html and 'wamp server',editor: 'Macromedia Dreamweaver',browser: 'Mozilla Firefox';
i want to read data(semister results) from table,and display data through bar chart like,
Database name exam
Table name 'sem_result' contain following columns>> regno[Primary key], uid, reg_date, exam_date, sem, result;
php code is::
<?php
// Connect to server
$cn=mysql_connect("localhost", "root", "");
//Connect to Database
mysql_select_db("exam") or die(mysql_error());
//sql query
$sql="SELECT result FROM sem_result WHERE uid=11111";
//collect results
$result=mysql_query($sql,$cn);
//read data if found
$counter=0;
while($rd=mysql_fetch_array($result))
{
$sem_result[$counter]=$rd[0]; //save sem results into array
$counter=$counter+1;
}
//display
echo "<table>
<tr>
<td>sem1</td>
<td width='100px'>
<img src='img/menu_back.png' width='".$sem_result[0]."%' height='15px'/>
</td>
<td>".$sem_result[0]."%</td>
</tr>
<tr>
<td>sem2</td>
<td width='100px'>
<img src='img/menu_back.png' width='".$sem_result[1]."%' height='15px'/>
</td>
<td>".$sem_result[1]."</td>
</tr>
</table>";
//close database
mysql_close($cn);
?>
if results are 78.95%,78.10% ,bar chart shows both result are equal, i.e 78%; image width become 78%,not 78.95% please help to fix this problem.
change table name and column name and progress.png image.
after that use it.
`
<?php $s="select count(*) as tnum from leakage";
$r=mysql_query($s) or die (mysql_error());
while($rw=mysql_fetch_array($r))
{
echo $tno=$rw['tnum'];
}
?>
<table class="table table-hover">
<thead>
<tr>
<th>DEPARTMENT</th>
<th>No.Of Leakage</th>
</tr>
</thead>
<?php
$sql1="select dept,count(dept) as total from leakage where dept='winding'";
$result1=mysql_query($sql1) or die(mysql_error());
while($row=mysql_fetch_array($result1))
{
$dept=$row['dept'];
$tot=$row['total'];
}
?>
<tr>
<td><?php echo $dept; ?></td>
<td width="100%"><img src="assets/images/progress.png" width="<?php echo (($tot/$tno)*100);?>" height="20px"><?php echo $tot;?>%</td>
</tr>
<?php
$sql2="select dept,count(dept) as total from leakage where dept='spining'";
$result2=mysql_query($sql2) or die(mysql_error());
while($row=mysql_fetch_array($result2))
{
$dept=$row['dept'];
$tot=$row['total'];
}
?>
<tr>
<td><?php echo $dept; ?></td>
<td width="100%"><img src="assets/images/progress.png" width="<?php echo (($tot/$tno)*100);?>" height="20px"><?php echo $tot;?>%</td>
</tr>
<?php
$sql5="select count(dept) as total from leakage";
$result5=mysql_query($sql5) or die(mysql_error());
while($row=mysql_fetch_array($result5))
{
$tot=$row['total'];
}
?>
<tr>
<td>Total</td>
<td width="100%"><img src="assets/images/progress.png" width="<?php echo $tot;?>" height="20px"><?php echo $tot; ?></td>
</tr>
</table>
`
As #hakre already pointed out, you can't get any more precise than a single pixel or percentage, ie you can't have 78.5px or 78.5%... however, you still have some options without javascript. First, I'm not sure why you are using an image for the green bar, why not just pure html/css? Either way, here's my suggestion:
Get the total width of the bar graph, from 0 - 100, in pixels. Just by eyeballing the image you posted, I'm gonna call it 325px:
$total_width = '325';
Then, set each bar's width as such:
$bar_width = round($total_width * ($sem_result[0] / 100));
This way, a stored value of 78.10% will end up as 254px, and 78.95% will be 257px. It is still not the exact percentage, but it is closer. The longer the total width of your graph, the more precise you calculation will be.

Download excel table via ajax

Im trying to download an excel file using a post request.. i was wondering if this could only be done using some sort of a hidden iframe or maybe using flash as i have read in some post however im not sure how to do this. This is the code i have so far..
employeeExcel.php
<?php
require_once ("../models/employeesModel.php");
header("Content-type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=reporteEmpleados.xls");
$employees = new Employee();
$emp = $employees->search_empleados();
?>
<html>
<body>
<table id="myTable" class="tablesorter">
<thead>
<tr>
<th>Nombre</th>
<th>Apellido</th>
<th>Tipo Doc.</th>
<th>Email</th>
</tr>
</thead>
<?php
foreach ($emp as $datos) {
$id = $datos["id_employee"];
$image = $datos["image"];
$name = $datos["employee_name"];
$surname = $datos["employee_surname"];
$dni = $datos["dni"];
$email = $datos["email"];
?>
<tbody>
<tr id="<?php echo $id; ?>">
<td> <?php echo $name; ?></td>
<td> <?php echo $surname; ?></td>
<td> <?php echo $dni; ?></td>
<td> <?php echo $email; ?></td>
</tr>
</tbody>
<?php
}
?>
</table>
<button onclick="employeeExcel();
return false" name="export">Export</button></a>
Here is where i do the ajax post
function employeeExcel() {
var uri = "employees.php";
$.ajax({
url: uri,
type: 'POST',
data: datos,
success: function() {
window.location = uri;
}
});
}
The file is not empty, but just in the wrong format.
HTML marks for tables (<tr><td>...) are not recognized as Excel file syntax. You need to create a real Excel file to use extension .xls of the output file.
For example, try to rename the file extension of the downloaded file with .txt instead of .xls and open it. You will see the HTML table output, which is not Excel syntax.
Have a look on this excellent PHP library to generate Excel file http://phpexcel.codeplex.com/

Put records next to eachother in columns using mysql_fetch_array?

I use mysql_fetch_array to fetch data from a mysql results set:
while($row = mysql_fetch_array($qry_result)){
Next I would like to place the data into columns in a table, but maximum of two columns at each row.
So using a table:
<table>
<tr>
<td>Record Here</td>
<td>Record Here</td>
</tr>
<tr>
<td>Record Here</td>
<td>Record Here</td>
</tr>
<tr>
<td colspan="2">Record Here</td>
</tr>
As you see above, I want to loop the results and create table columns in the loop.
This so that the records line up two and two on a results page.
Remember, if there is an odd number of records, then the last table column would need a colspan of 2, or perhaps just use an empty column?
Anybody know how to do this?
If I use a for loop inside the while loop, I would just be lining up the same records x times for each while loop. Confusing...
Any ideas?
Thanks
Implement a (1-indexed) counter within the while loop. Then add (after the loop):
if ($counter%2)
echo '<td></td>';
This will leave an additional blank cell in your table if the last column contains only one row.
Something like this should work...
<table>
<?php
while(true) {
$row1 = mysql_fetch_array($qry_result);
if($row1 === false) break;
$row2 = mysql_fetch_array($qry_result);
if($row2 !== false) {
echo "<tr><td>$row1</td><td>$row2</td></tr>";
} else {
echo "<tr><td coslspan=\"2\">$row1</td></tr>";
break; // output the final row and then stop looping
}
}
?>
</table>
<table>
<tr>
<?
$i=1;
$num = mysql_num_rows($qry_result);
while($row = mysql_fetch_array($qry_result)){
if($i%2==1)
?>
<tr>
<?
?>
<td <? if($i==$num && $i%2==1)echo 'colspan="2"';?>><?=$row['keyName']?></td>
<?
if($i%2==0)
{
<?
</tr>
?>
}
$i++;
}
?>

Categories