Following is an example about exporting data to excel:
here is the key code:
如果需要控制导出数据在excel中的样式,则只需要给数据套上table样式即可。
1.report_inq.php:
<script language="javascript">
function export_excel(){
var part =document.all.part.value;
var id =document.all.id.value;
window.open('export_excel.php?part='+part+'&id='+id);
}
</script>
<?php
function db_link()
{
$access_id = "root";
$db_name = "db_name";
@ $db = mysql_connect('localhost', $access_id, '831025') or
die("Could not connect to database. ");
mysql_query("SET NAMES 'GBK'");
mysql_select_db($db_name);
return $db;
}
$link = db_link();
$id = $_POST['id'];
$part = $_POST['part'];
echo '<form name="form1" action="" method="post" οnsubmit="return check(this);">';
echo '<input type="text" name="id" size="8" maxlength="8" value="'.$id.'"></input>';
echo '<input type="text" name="part" size="8" maxlength="20" value="'.$part.'"></input>';
echo '<input type="submit" name="search" value="Search">';
echo '</form>';
if ($_POST['search'] == 'Search'){
$sql = "SELECT * FROM test_table WHERE id='".$id."' AND part='".$part."' ";
$res = mysql_query($sql);
//display something here
echo '<input type="button" name="export" οnclick="export_excel();" value="Export" >';
}
?>
2.export_excel.php:
<?php
$id = $_GET['id'];
$part = $_GET['part'];
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");;
header("Content-Disposition: attachment;filename=mrp_report.xls ");
header("Content-Transfer-Encoding: binary ");
echo '<table border=1>';
echo '<tr bgcolor="red">';
echo "<th>Date</th>
<th>Line</th>
<th>Req</th></tr>";
$sql = "SELECT * FROM test_table WHERE part='".$part."' AND id='".$id."' ";
$res = mysql_query($sql);
$num = mysql_num_rows($res);
if($num>0){
for($i=0;$i<$num;$i++){
$row = mysql_fetch_array($res);
echo '<tr><td>'.$row['date']."</td>";
echo '<td>'.$row['line']."</td>";
echo '<td>'.$row['req']."</td></tr>";
}
}
echo '</table>';
?>