PHP+MySQL导出Excel的方法

前段时间接了个任务,其中有需要把数据库中的内容导出Excel表格,调了几天的BUG终于完成,下面说一下过程:

1. 导出Excel需要下载PHPExcel包,因为要用到里面的一些头文件。下载网址:http://phpexcel.codeplex.com/

下载完成后要把它和你写的PHP文件在一起,或者其中引用的部分的路径一定要正确,否则会报错。

 

2. 代码中要包含一些必要的 header 文件:

 header("Content-Type: text/html;charset=utf-8");
  header('Content-Type: application/vnd.ms-excel');
  header('Content-Disposition: attachment;filename="成员工作量.xls"');
  header('Cache-Control: max-age=0');
 
  header('Cache-Control: max-age=1');

  header ('Expires: Mon, 26 Jul 2014 05:00:00 GMT');
  header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
  header ('Cache-Control: cache, must-revalidate');
  header ('Pragma: public');

可能其中的一些可有可无,但一些必要的还是要有的,这里就不一一解释每句代码的意思了。

 

3. 用 PHPExcel 时要先new一个对象:

 $objPHPExcel = new PHPExcel(); 

然后利用此对象对Excel表进行相应的操作。

 

下面是对Excel的一些属性的操作:

 $objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
                                                          ->setLastModifiedBy("Maarten Balliauw")
                                                          ->setTitle("Office 2007 XLSX Test Document")
                                                          ->setSubject("Office 2007 XLSX Test Document")
                                                          ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
                                                          ->setKeywords("office 2007 openxml php")
                                                          ->setCategory("Test result file");

 

当要对其中的单元格操作时,要用到setCellValue()函数,如对A1格赋值:

$objPHPExcel->setActiveSheetIndex(0)
                          ->setCellValue('A1', '序号');

4.设置表格宽度:

如:设置B列的列宽为20:$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(20);

 

当要想把字符串放到表格时,要先转换类型:

$user = iconv("GBK","UTF-8",$row['user']);  //$row['user']是从数据库中取得变量

然后插入:

$objPHPExcel->setActiveSheetIndex(0)
                          ->setCellValue('A1', $user);

最后转换:

$objPHPExcel->getActiveSheet()
                          ->getCell('A1')->setValueExplicit($user, PHPExcel_Cell_DataType::TYPE_STRING);

 

5.关于导出的Excel的乱码问题:

 

因为Excel默认的是GBK编码,因此在填入内容之前要先转换编码类型:

 

首先,此页面的编码要用GBK:

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

当用的是notepad++开发时,选择“以utf-8无BOM格式”。

 

然后是向数据库发请求时用gbk:

mysql_query("set names 'gbk'");

 

最后是不要随意引用文件,如:链接数据库的文件:conn.php ,因为两者的编码不一样,会出现乱码,所以最好把引用的文件内容复制过来。

 

下面附上一段例子代码:

<?php

  error_reporting(E_ALL);
  ini_set('display_errors', TRUE);
  ini_set('display_startup_errors', TRUE);
  date_default_timezone_set('Europe/London');

  if (PHP_SAPI == 'cli')
     die('This example should only be run from a Web Browser');

  require_once('PHPExcel.php');

  $objPHPExcel = new PHPExcel();

  $objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
        ->setLastModifiedBy("Maarten Balliauw")
        ->setTitle("Office 2007 XLSX Test Document")
        ->setSubject("Office 2007 XLSX Test Document")
        ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
        ->setKeywords("office 2007 openxml php")
        ->setCategory("Test result file");

  $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', '序号')
            ->setCellValue('B1', '学号')
            ->setCellValue('C1', '姓名')
   ->setCellValue('D1', '部门')
            ->setCellValue('E1', '工作量');
   
 $con = mysql_connect("localhost","root","123");
        if (!$con)
        {
            die('Could not connect: ' . mysql_error());
        }
    mysql_select_db("outuser", $con);    
    mysql_query("set names 'gbk'");
    $sql="SELECT * FROM work WHERE state='1' ORDER BY id desc";    
    $result=mysql_query($sql);
    $i = 2;
    $id = 1;
    while($row=mysql_fetch_array($result))
    {
        switch($row['department'])
  {
      case "content":
       $row['department'] = "内容部";
    break;
   case "operate":
       $row['department'] = "运营部";
    break;
   case "front":
       $row['department'] = "技术部前端";
    break;
   case "backstage":
       $row['department'] = "技术部后台服务器";
    break;
   case "move":
       $row['department'] = "技术部移动";
    break;
   case "page":
       $row['department'] = "技术部页面";
    break;
  }

  $user = iconv("GBK","UTF-8",$row['user']);
  $name = iconv("GBK","UTF-8",$row['name']);
  $work = iconv("GBK","UTF-8",$row['work']);

        $objPHPExcel->setActiveSheetIndex(0)
                    ->setCellValue('A'.$i, $id)
                    ->setCellValue('B'.$i, $user)
                    ->setCellValue('C'.$i, $name)
        ->setCellValue('D'.$i, $row['department'])
                    ->setCellValue('E'.$i, $work);
       
  $objPHPExcel->getActiveSheet()
              ->getCell('B'.$i)->setValueExplicit($user, PHPExcel_Cell_DataType::TYPE_STRING);
        $objPHPExcel->getActiveSheet()
              ->getCell('C'.$i)->setValueExplicit($name, PHPExcel_Cell_DataType::TYPE_STRING);
  $objPHPExcel->getActiveSheet()
              ->getCell('E'.$i)->setValueExplicit($work, PHPExcel_Cell_DataType::TYPE_STRING);
           
        $i++;
        $id++; 
    }
 mysql_close($con);
 
 $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(20);
 $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(20);
 
    $objPHPExcel->getActiveSheet()->setTitle('Simple');

    $objPHPExcel->setActiveSheetIndex(0);
  header("Content-Type: text/html;charset=gbk");
  header('Content-Type: application/vnd.ms-excel');
  header('Content-Disposition: attachment;filename="成员工作量.xls"');
  header('Cache-Control: max-age=0');
 
  header('Cache-Control: max-age=1');

  header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
  header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
  header ('Cache-Control: cache, must-revalidate');
  header ('Pragma: public');

  $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
  $objWriter->save('php://output');
?>

 

你可能感兴趣的:(PHP+MySQL导出Excel的方法)