Zend framework 无法通过Zend Framework导出到excel 2010学生版

Zend framework 无法通过Zend Framework导出到excel 2010学生版,zend-framework,Zend Framework,我正在尝试将数据导出到ms excel,我已经为我的应用程序准备了Office 2010学生版,方法是跟随Pablo Viquez的帖子 然而,我无法让它工作以下情况发生 1.在地址栏中输入reports/report/TodaysAppointsReport/format/excel时,工作簿将尝试另存为excel.xls 2.当我打开文件时,Excel会给我以下警告:您试图打开的文件“Excel.xls”的格式与文件扩展名指定的格式不同。请在打开文件之前验证该文件是否已损坏且来源可靠 打开文

我正在尝试将数据导出到ms excel,我已经为我的应用程序准备了Office 2010学生版,方法是跟随Pablo Viquez的帖子

然而,我无法让它工作以下情况发生

1.在地址栏中输入reports/report/TodaysAppointsReport/format/excel时,工作簿将尝试另存为excel.xls

2.当我打开文件时,Excel会给我以下警告:您试图打开的文件“Excel.xls”的格式与文件扩展名指定的格式不同。请在打开文件之前验证该文件是否已损坏且来源可靠

  • 打开文件时,显示的是我的TodaysAppointsReport.export.phtml文件中的代码
  • 谁能告诉我哪里出了问题,因为我需要让它工作

    我可以验证查询是否有效,以及数据是否显示在屏幕上的my TodaysAppointsReport.phtml文件中。我还可以验证该组件是否与它所依赖的OLE组件一起安装在pear中

    我的控制器代码

    class Reports_ReportController extends Zend_Controller_Action 
     { 
      public function init() 
      { 
    
           // Excel format context 
                $excelConfig = 
                array('excel' => array 
                                                ('suffix'  => 'excel', 
                                                        'headers' => array( 
                                                                                        'Content-type' => 'application/vnd.ms-excel')), 
                ); 
    
           //initalise context switch 
           $contextSwitch = $this->_helper->contextSwitch(); 
    
           // Add the new context 
                $contextSwitch->setContexts($excelConfig); 
    
    
    
                // Set the new context to the reports action 
                $contextSwitch->addActionContext('todaysappointmentsreport', 'excel'); 
    
                $contextSwitch->initContext(); 
    
    } 
    
     // action to redirect user straight to login page 
     public function preDispatch() 
     { 
       // set admin layout 
      // check if user is authenticated 
      // if not, redirect to login page 
      $url = $this->getRequest()->getRequestUri();           
      if (!Zend_Auth::getInstance()->hasIdentity()) { 
      $session = new Zend_Session_Namespace('petmanager.auth'); 
      $session->requestURL = $url; 
      $this->_redirect('/login'); 
     } 
        } 
    
     // report to print todays appointments 
     public function todaysappointmentsreportAction() 
     { 
         $t=date('y-m-d'); 
                $q = Doctrine_Query::create()   
                        ->from('PetManager_Model_Groomappointments g') 
            ->leftJoin('g.PetManager_Model_Clients c') 
                        ->leftJoin('g.PetManager_Model_Pets p') 
                        ->leftJoin('g.PetManager_Model_Users u') 
                        ->leftJoin('g.PetManager_Model_Groomservices s') 
                        ->leftJoin('s.PetManager_Model_Groomprocedures r') 
                        ->where('g.gapmtStatus = 1 AND g.gapmtDate = ?',$t) 
                        ->orderBy('g.gapmtSTime,g.gapmtSTime,u.name'); 
                         $result = $q->fetchArray(); 
                         if (count($result) >= 1) { 
                         $this -> view -> records = $result;             
                         } 
    
    }   
    
    我的TodaysAppointsReport.excel.phtml代码正如我所说,这是我打开excel文件时显示在该文件中的代码

     // Change error reporting for compatibility 
     // Spreadsheet Excel Writter was built using PHP4, 
     // so there's a lot of DEPRECATED notices 
       error_reporting(E_ERROR | E_WARNING | E_PARSE); 
    
     /** 
     * PEAR package 
     * 
     * @link http://pear.php.net/package/Spreadsheet_Excel_Writer
     * @see PEAR/Spreadsheet/Excel/Writer.php 
     */ 
     require_once 'Spreadsheet/Excel/Writer.php'; 
    
     // Lets define some custom colors codes 
     define('CUSTOM_DARK_BLUE', 20); 
     define('CUSTOM_BLUE', 21); 
     define('CUSTOM_LIGHT_BLUE', 22); 
     define('CUSTOM_YELLOW', 23); 
     define('CUSTOM_GREEN', 24); 
    
    // First, we create a Workbook 
    $workbook = new Spreadsheet_Excel_Writer(); 
    
     // Add one sheet, called: Users Report 
     $worksheet = &$workbook->addWorksheet('Todays Grooming Appointments Report'); 
    
     // Create the custom colors on our new workbook 
     // This function takes 4 params: 
     //    - Code index [1 to 64] 
     //    - RGB colors (0-255) 
      $workbook->setCustomColor(CUSTOM_DARK_BLUE, 31, 73, 125); 
      $workbook->setCustomColor(CUSTOM_BLUE, 0, 112, 192); 
      $workbook->setCustomColor(CUSTOM_LIGHT_BLUE, 184, 204, 228);  
      $workbook->setCustomColor(CUSTOM_YELLOW, 255, 192, 0); 
      $workbook->setCustomColor(CUSTOM_GREEN, 0, 176, 80); 
    
      // Lets hide gridlines 
      //$worksheet->hideScreenGridlines(); 
    
      // Lets create some custom styles 
      $formatHeader = &$workbook->addFormat(); 
      $formatHeader = 
      &$workbook->addFormat( 
        array('Size'    => 16, 
              'VAlign'  => 'vcenter', 
              'HAlign'  => 'center', 
              'Bold'    => 1, 
              'Color'   => 'white', 
              'FgColor' => CUSTOM_DARK_BLUE)); 
    
       $formatReportHeader = 
       &$workbook->addFormat( 
        array('Size'     => 9, 
              'VAlign'   => 'bottom', 
              'HAlign'   => 'center', 
              'Bold'     => 1, 
              'FgColor'  => CUSTOM_LIGHT_BLUE, 
              'TextWrap' => true)); 
    
       $formatData = 
        &$workbook->addFormat( 
          array( 
            'Size'   => 8, 
            'HAlign' => 'center', 
            'VAlign' => 'vcenter')); 
    
       /** 
       * First, format the worksheet, adding the headers 
       * and row/columns custom sizes 
       */ 
    
       // Create a nice header with a dark blue background 
       // The function setRow takes 3 parameters: 
       //    - row index 
       //    - row height 
       //    - Format to apply to row [Optional] 
       $worksheet->setRow(0, 11, $formatHeader); 
       $worksheet->setRow(1, 46, $formatHeader); 
       $worksheet->setRow(2, 11, $formatHeader); 
       $worksheet->setRow(3, 11, $formatHeader); 
       $worksheet->setRow(4, 11, $formatHeader); 
    
    // Set the size of the columns 
    // The function setColumn takes 5 params: 
    //     - First column 
    //     - Last column 
    //     - Column Width 
    //     - Format [Optional, default = 0] 
    //     - Hidden [Optional, default = 0] 
     $worksheet->setColumn(0, 0, 7); //  shrink it to 7 
     $worksheet->setColumn(1, 1, 12); // set the width to 12 
     $worksheet->setColumn(1, 1, 15); // set the width to 15 
     $worksheet->setColumn(1, 1, 15); // set the width to 15 
     $worksheet->setColumn(1, 1, 15); // set the width to 15 
    
    /** 
    * 
    * Once we have the format ready, add the text to the spreadsheet 
    * 
    */ 
    // Write a text header 
    $worksheet->write(1, 1, 'Todays Grooming Appointments Report', $formatHeader); 
    
     // Create the header for the data starting @ row 6
     $indexCol = 0; 
     $indexRow = 6; 
     $worksheet->write($indexRow, $indexCol++, 'Scheduled Time', $formatReportHeader); 
     $worksheet->write($indexRow, $indexCol++, 'Client', $formatReportHeader); 
     $worksheet->write($indexRow, $indexCol++, 'Pet', $formatReportHeader); 
     $worksheet->write($indexRow, $indexCol++, 'Procedure', $formatReportHeader); 
     $worksheet->write($indexRow, $indexCol++, 'Groomer', $formatReportHeader); 
    
     $indexRow++;   // Advance to the next row 
     $indexCol = 0; // Start @ column 0 
    
     // Print the report data 
     if(count($this->records) == 0) { 
      // No data 
      $worksheet->write( 
        $indexRow, 
        $indexCol, 
        'No Appointments', 
        $formatData); 
    
     } else { 
      // Write the data 
       foreach ($this->records as $r) { 
        $worksheet->write( 
            $indexRow, 
            $indexCol++, 
            $this->$r['gapmtSTime'] - $this->substr$r['gapmtETime'], 
            $formatData); 
    
        $worksheet->write( 
            $indexRow, 
            $indexCol++, 
            $this->$r['PetManager_Model_Clients']['firstName'] $this->$r ['PetManager_Model_Clients']['lastName'], 
            $formatData); 
    
        $worksheet->write( 
            $indexRow, 
            $indexCol++, 
            $this->$r['PetManager_Model_Pets']['name'], 
            $formatData); 
    
            $worksheet->write( 
            $indexRow, 
            $indexCol++, 
            $this->$r['PetManager_Model_Groomservices']['PetManager_Model_Groomprocedures']['groomprocedure'], 
            $formatData); 
    
                $worksheet->write( 
            $indexRow, 
            $indexCol++, 
            $this->$r['PetManager_Model_Users']['name'], 
            $formatData);   
    
        // Advance to the next row 
         $indexRow++; 
      } 
     } 
    
     /** 
     * 
     * Response with the excel file 
     * 
     */ 
    
     // Sends HTTP headers for the Excel file. 
     $workbook->send('todaysappointmentsreport.xls'); 
    
    // Calls finalization methods. 
    // This method should always be the last one to be called on every workbook 
    $workbook->close();
    

    我正在为我自己的项目做一个类似的例子,所以如果我发现了一个解决方案,我会用任何结果更新这个线程

    这里有一篇关于contextSwitch视图帮助器的有用文章(maltblue),它更深入地解释了帮助器

    最后,我通过将标题直接放在控制器操作中,成功地导出为csv ok,如下所示

    在我的行动中

    //create the csv file header and filename based on the action name
        $actionName = $this->getRequest()->getActionName();
        new Admin_Model_Resource_csvFileHeader( $actionName );
    
    此处的其余代码用于获取要传递到视图文件的数据

    管理模型资源如下所示,因此它可以由任何控制器操作使用

    class Admin_Model_Resource_csvFileHeader
    
    {

    private$\u csvFileNameFromAction=null;
    /**
    *从操作名称创建csv文件名的第一部分
    *@param$actionName-报告的控制器操作的名称
    */
    公共函数构造($actionName)
    {
    $this->\u csvFileNameFromAction=$actionName;
    $this->generateCsvHeader();
    }
    /**
    *方法直接从构造函数调用
    *集中csv文件头并使其一致
    *因此,它最大限度地实现了代码重用
    *@return null-只需生成csv头
    */
    公共函数generateCsvHeader()
    {
    $dateSuffix=date('d-m-Y',time());
    $csvFileName=$this->\u csvFileNameFromAction.“'.'.$dateSuffix;
    标题('Content-Type:text/x-csv;name=“”.$csvFileName..csv“);
    标题('Content-Disposition:inline;filename=“”.$csvFileName..csv“);
    标题(“Pragma:public”);
    标题('Last-Modified:'.gmdate('D,dm Y H:i:s')。'GMT');
    标头('Cache-Control:无存储,无缓存,必须重新验证');
    标头(“缓存控制:预检查=0,后检查=0,最大使用期限=0”);
    标题(“内容传输编码:无”);
    }
    

    }

    确保“TodaysAppointsReport.excel.phtml”视图文件的内容包含在php开始和结束标记中。

    我已经阅读了那篇文章,非常好,非常感谢您的任何输入。由于时间限制,我为我的项目做了一个变通,我创建了一个包含查询结果的xml文件,然后将其导入excel。我也遇到了这个问题,然后改为PHPExcel()。在我看来,这个库比电子表格\u Excel\u Writer好得多。。。
    public function indexAction()
    {
        $this->filename = "/excel-" . date( "m-d-Y" ) . "-".mt_rand(10000,20000).".xls";
    
        $realPath = realpath($this->filename);
        if (false === $realPath )
        {
            touch($this->filename);
            chmod($this->filename, 0777); 
        }
    
        $this->filename = realpath( $this->filename );
        $this->handle = fopen( $this->filename, "w" );
    
        $projectsModul = new Model_DbTable_Projects();
        $projects = $projectsModul->fetchProjects();
    
        foreach ($projects->toArray() as $row)
        {
            $this->finalData[] = array(
                $row['id'],
                $row['company'],
                $row['project'],
                $row['start'],
                $row['end']
            );
        }
    
        foreach ( $this->finalData AS $finalRow )
        {
            fputcsv( $this->handle, $finalRow, "\t" );
        }
    
        fclose( $this->handle );
    
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender();
    
        $this->getResponse()->setRawHeader( "Content-Type: application/vnd.ms-excel; charset=UTF-8")
            ->setRawHeader("Content-Disposition: attachment; filename=excel.xls")
            ->setRawHeader("Content-Transfer-Encoding: binary")
            ->setRawHeader("Expires: 0")
            ->setRawHeader("Cache-Control: must-revalidate, post-check=0, pre-check=0")
            ->setRawHeader("Pragma: public")
            ->setRawHeader("Content-Length: " . filesize($this->filename))
            ->sendResponse();
    
        readfile($this->filename); 
        exit();
    }
    
    public function indexAction()
    {
        $this->filename = "/excel-" . date( "m-d-Y" ) . "-".mt_rand(10000,20000).".xls";
    
        $realPath = realpath($this->filename);
        if (false === $realPath )
        {
            touch($this->filename);
            chmod($this->filename, 0777); 
        }
    
        $this->filename = realpath( $this->filename );
        $this->handle = fopen( $this->filename, "w" );
    
        $projectsModul = new Model_DbTable_Projects();
        $projects = $projectsModul->fetchProjects();
    
        foreach ($projects->toArray() as $row)
        {
            $this->finalData[] = array(
                $row['id'],
                $row['company'],
                $row['project'],
                $row['start'],
                $row['end']
            );
        }
    
        foreach ( $this->finalData AS $finalRow )
        {
            fputcsv( $this->handle, $finalRow, "\t" );
        }
    
        fclose( $this->handle );
    
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender();
    
        $this->getResponse()->setRawHeader( "Content-Type: application/vnd.ms-excel; charset=UTF-8")
            ->setRawHeader("Content-Disposition: attachment; filename=excel.xls")
            ->setRawHeader("Content-Transfer-Encoding: binary")
            ->setRawHeader("Expires: 0")
            ->setRawHeader("Cache-Control: must-revalidate, post-check=0, pre-check=0")
            ->setRawHeader("Pragma: public")
            ->setRawHeader("Content-Length: " . filesize($this->filename))
            ->sendResponse();
    
        readfile($this->filename); 
        exit();
    }