Home > php教程 > php手册 > 保存数据库查询结果到Excel

保存数据库查询结果到Excel

WBOY
Release: 2016-06-13 09:38:03
Original
1026 people have browsed it

Excel可以很方便地处理数据,数据库的数据如果能够读取成excel文件,会很方便地进行处理。

实现数据库数据到Excel的转换类excel.php

<?php
class excel
{ 
   function start()
    {
      ob_start();
     }
    function save($path)
      {
        $data = ob_get_contents();
        ob_end_clean();
        $this->wirtetoexcel($path,$data);
     }
   function wirtetoexcel ($fn,$data)
     {
       $fp=fopen($fn,"wb");
       fwrite($fp,$data);
       fclose($fp);
    }
}
?>
Copy after login

创建这个类的对象,再调用这个对象的方法,即可实现数据库数据导出为Excel。

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">  
<link href="css/style.css" rel="stylesheet" type="text/css" />  
<?php   
include("conn.php");  
$query=mysql_query("select * from map order by register_date desc") ;   
$i=$perpagenum*($page-1)+1;   
include_once("excel.php");
$Excel=new Excel();
$Excel->start();
?>
<table width="600" border="0">  
	<tr>  
    <td align="center">companyname_cn</td>  
    <td align="center">companyname_en"</td>  
    <td align="center">name</td>  
    <td align="center">position</td>  
    <td align="center">tel</td>  
    <td align="center">fax</td>  
    <td align="center">email</td>  
    <td align="center">website</td>  
    <td align="center">product</td>  
  </tr> 
<?php
while($myrow = mysql_fetch_array($query)){   
?>  
  <tr>  
    <td align="center"><?php echo $myrow["companyname_cn"]; ?></td>  
    <td align="center"><?php echo $myrow["companyname_en"]; ?></td>  
    <td align="center"><?php echo $myrow["name"]; ?></td>  
    <td align="center"><?php echo $myrow["position"]; ?></td>  
    <td align="center"><?php echo $myrow["tel"]; ?></td>  
    <td align="center"><?php echo $myrow["fax"]; ?></td>  
    <td align="center"><?php echo $myrow["email"]; ?></td>  
    <td align="center"><?php echo $myrow["website"]; ?></td>  
    <td align="center"><?php echo $myrow["product"]; ?></td>  
  </tr>  
<? }  
?>  
</table>  
<p>  
<?php   
	$Excel->save("Excel/data.xls"); 
?>  
</p>
Copy after login

关键代码其实就几行:

// 包含类文件
include_once("excel.php");
// 创建excel类的对象
$Excel=new Excel();
// 调用对象 $Excel 的 start()方法
$Excel->start();
// 调用对象的 save() 声称 excel 文件。
$Excel->save("Excel/data.xls");
Copy after login
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template