phpStudy6——php导出可以设置样式的excel表格

前言:

一般的后台管理页面肯定少不了excel表格导出的功劳,尤其是那些电商平台的订单导入导出,用户列表的导入导出等,那么本文就介绍php是如何导出excel表格的。

php导出excel方法有很多,网上介绍比较多的是php默认的设置header的方法,以及使用phpexcel库。本文以php默认的方法为例进行演示,有感兴趣的可以去了解下phpexcel库的使用。

示例代码:

输出静态内容的表格:

 1 <style>
 2 /*设置表格样式*/
 3 table {
 4     border-top: 1px solid #2af;
 5       border-left: 1px solid #2af;
 6 }
 7 .title{
 8     background:#2af;
 9     color:#FFFFFF;
10     font-weight:bold;
11 }
12 td {
13     text-align: center;
14     font-size: 12px;
15     font-family: Arial, Helvetica, sans-serif;
16     color: #152122;
17 }
18 td, th {
19     padding: 5px;
20     border: 0.05em solid #2af;
21     border-left: 0;
22     border-top: 0;
23 }
24 </style>
25 <?php
26 //设置当前内容类型为excel表格,并设置文件扩展名为xls
27 header ( "Content-type:application/vnd.ms-excel" );
28 header ( "Content-Disposition:filename=csat.xls" );
29 
30 //输出表格
31 echo "<table width='800' border='0' cellspacing='0' cellspadding='0'>
32   <tr>
33     <th class='title'>编号</th>
34     <th class='title'>姓名</th>
35     <th class='title'>手机号码</th>
36   </tr>
37   <tr>
38     <td>1001</td>
39     <td>张三</td>
40     <td>13598759865</td>
41   </tr>
42   <tr>
43     <td>1002</td>
44     <td>李四</td>
45     <td>15698789658</td>
46   </tr>
47 </table>";
48 ?>

实例解析:

关键代码:

1 //输出表格页面的头部及样式
2 header ( "Content-type:application/vnd.ms-excel" );
3 header ( "Content-Disposition:filename=csat.xls" );

其实这个和前边输出html内容的设置类似

 1 header("Content-Type:text/html;charset=utf8");  

将数据库查询的数据导出到excel表格:

关键代码:

 1 // 输出每行数据
 2 while($row =mysql_fetch_array($result)) {
 3     $userScore=(int)$row["userScore"];
 4     $scoreLevel="";
 5     if($userScore<60) $scoreLevel="三等奖";
 6     if($userScore<100&&$userScore>=60) $scoreLevel="二等奖";
 7     if($userScore>=100) $scoreLevel="一等奖";
 8             
 9     echo ' <tr><td>';
10     echo $row["userId"];
11     echo'</td><td>';
12     echo $row["userName"];
13     echo'</td><td>';
14     echo $row["phoneNumber"];
15     echo'</td><td>';
16     echo $row["userScore"];
17     echo'</td><td>';
18     echo $scoreLevel;
19     echo'</td><td>';
20     echo $row["dataTime"];
21     echo '</td></tr>';        
22 }

 

posted on 2016-07-07 15:47  逍遥云天  阅读(1794)  评论(0编辑  收藏  举报

导航