php操作excel

介绍一个比较强大的php的excel库-PHPExcel

下载连接:

http://download-codeplex.sec.s-msft.com/Download/Release?ProjectName=phpexcel&DownloadId=504322&FileTime=129946319318670000&Build=20337

再提供一段例子代码,数据库表中的数据导入到一个execel中

<?php
$dbhost = “localhost”;
$dbuser = “xxx”; //用户名
$dbpass = “xxx”; //密码
$dbname = “xx”; //数据库的名字

mysql_connect($dbhost,$dbuser,$dbpass);
mysql_select_db($dbname);

// require the PHPExcel file
require_once ‘../Classes/PHPExcel.php’;

// simple query

$query = “SELECT * FROM towncouncil ORDER by id DESC”;
$headings = array(‘code’, ‘abbr’,’name’);

if ($result = mysql_query($query) or die(mysql_error())) {
    // Create a new PHPExcel object
    $objPHPExcel = new PHPExcel();
    $objPHPExcel->getActiveSheet()->setTitle(‘List of Users’);

    $rowNumber = 1;
    $col = ‘A’;
    foreach($headings as $heading) {
       $objPHPExcel->getActiveSheet()->setCellValue($col.$rowNumber,$heading);
       $col++;
    }

    // Loop through the result set
    $rowNumber = 2;
    while ($row = mysql_fetch_row($result)) {
       $col = ‘A’;
       foreach($row as $cell) {
          $objPHPExcel->getActiveSheet()->setCellValue($col.$rowNumber,$cell);
          $col++;
       }
       $rowNumber++;
    }

    // Freeze pane so that the heading line will not scroll
    $objPHPExcel->getActiveSheet()->freezePane(‘A2’);

    // Save as an Excel BIFF (xls) file
    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, ‘Excel5’);

   header(‘Content-Type: application/vnd.ms-excel’);
   header(‘Content-Disposition: attachment;filename=”userList.xls”‘);
   header(‘Cache-Control: max-age=0’);

   $objWriter->save(‘php://output’);
   exit();
}
echo ‘a problem has occurred… no data retrieved from the database’;
?>

最后会弹出一个框叫用户保存文件。

版权所有,禁止转载. 如需转载,请先征得博主的同意,并且表明文章出处,否则按侵权处理.

    分享到:

留言

你的邮箱是保密的 必填的信息用*表示