第1步:在鍵值對中獲取MySql數據。
Array
(
[14] => Array
(
[Name] => Parvez Alam
[Age] => 21
[Gender] => Male
)
[15] => Array
(
[Name] => Shavez Alam
[Age] => 21
[Gender] => Male
)
)
第2步:PHP代碼來獲取選項類型和力到瀏覽器下載文件,而不是顯示。
if(isset($_POST["ExportType"]))
{
switch($_POST["ExportType"])
{
case "export-to-excel" :
// Submission from
$filename = $_POST["ExportType"] . ".xls";
header("Content-Type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=\"$filename\"");
ExportFile($data);
//$_POST["ExportType"] = '';
exit();
default :
die("Unknown action : ".$_POST["action"]);
break;
}
}
function ExportFile($records) {
$heading = false;
if(!empty($records))
foreach($records as $row) {
if(!$heading) {
// display field/column names as a first row
echo implode("\t", array_keys($row)) . "\n";
$heading = true;
}
echo implode("\t", array_values($row)) . "\n";
}
exit;
}
步驟3:定義用於表和按鈕顯示數據的HTML佈局火出口到CSV動作。
<div><a href="javascript:void(0)" id="export-to-excel">Export to excel</a></div>
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post" id="export-form">
<input type="hidden" value='' id='hidden-type' name='ExportType'/>
</form>
<table id="" class="table table-striped table-bordered">
<tr>
<th>Name</th>
<th>Status</th>
<th>Priority</th>
<th>Salary</th>
</tr>
<tbody>
<?php foreach($data as $row):?>
<tr>
<td><?php echo $row ['Name']?></td>
<td><?php echo $row ['Status']?></td>
<td><?php echo $row ['Priority']?></td>
<td><?php echo $row ['Salary']?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
第4步:現在我們將使用jQuery的代碼來獲取點擊的事件。
<script type="text/javascript">
$(document).ready(function() {
jQuery('#Export to excel').bind("click", function() {
var target = $(this).attr('id');
switch(target) {
case 'export-to-excel' :
$('#hidden-type').val(target);
//alert($('#hidden-type').val());
$('#export-form').submit();
$('#hidden-type').val('');
break
}
});
});
</script>
檢查此鏈接http://only4ututorials.blogspot.in/2016/05/how-to-export-to- excel-in-codeigniter-3.html – 2016-05-02 05:06:14