NO数据使用PHPExcel库加载到Excel文件中

时间:2014-06-07 06:52:52

标签: php phpexcel

我需要什么:

  1. 点击导出标签数据从数据库加载到Excel文件中,格式如csv,xls等。
  2. 我的问题:

    • 在Excel文件中加载执行文件无数据时。

    这是我的代码段:

      error_reporting(E_ALL);
         ini_set('display_errors', TRUE);
        ini_set('display_startup_errors', TRUE);
        date_default_timezone_set('UTC');
    
        mysql_connect('localhost','root','') or die('Cannot connect to database !');
        mysql_select_db("atesting_ess") or die('No database found in mysql !');
    
       if (PHP_SAPI == 'cli')
        die('This example should only be run from a Web Browser');
    
            /** Include PHPExcel */
         require_once dirname(__FILE__) . '/../Classes/PHPExcel.php';
    
             // Create your database query
           $query = "SELECT * FROM asana_tasks";  
    
           // Execute the database query
            $result = mysql_query($query) or die(mysql_error());
    
           // Instantiate a new PHPExcel object
           $objPHPExcel = new PHPExcel(); 
          // Set the active Excel worksheet to sheet 0
          $objPHPExcel->setActiveSheetIndex(0); 
    
            $rowCount = 1; 
            while($row = mysql_fetch_array($result)){ 
        //print_r($row);
        $objPHPExcel->setActiveSheetIndex(0)
                    ->setCellValue('A'.$rowCount, $row['Projects_name'])
                    ->SetCellValue('B'.$rowCount, $row['Name']) 
                     ->SetCellValue('C'.$rowCount, $row['Priority']); 
    
                 $rowCount++; 
               } 
           // Redirect output to a client?s web browser (Excel2007)
         header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
         header('Content-Disposition: attachment;filename="01simple.xlsx"'); 
         header('Cache-Control: max-age=0');
         // If you're serving to IE 9, then the following may be needed
         header('Cache-Control: max-age=1');
    
    // If you're serving to IE over SSL, then the following may be needed
    header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
    header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
    header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
    header ('Pragma: public'); // HTTP/1.0
    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
    $objWriter->save('php://output');
    exit;
    
    1. 我试过通过添加虚拟数据来解决它的工作精细代码:

         // Add some data
           $objPHPExcel->setActiveSheetIndex(0)
          ->setCellValue('A1', 'Hello')
          ->setCellValue('B2', 'world!')
          ->setCellValue('C1', 'Hello')
          ->setCellValue('D2', 'world!');
      

1 个答案:

答案 0 :(得分:0)

由于列是A,B,C等而不是1,2,3等,因此将其转换为字符。下面的代码适用于A到Z列,AA,AB等,这需要扩展。

$columnvalue = strtoupper(chr($col) + 96));
$objPHPExcel->getActiveSheet()->setCellValue($columnvalue . $row, $value);