2011-06-01 33 views
1

我試圖導出數據到ms excel,我有我的應用程序的Office 2010學生版遵循Pablo Viquez的帖子http://www.pabloviquez.com/2009/08/export-excel-spreadsheets-using-zend-framework/通過Zend框架無法導出到excel 2010學生版

但我不能得到它的工作會發生以下情況

1.On進入報告/報告/ todaysappointmentsreport /格式/ EXCEL到工作簿試圖保存爲excel.xls地址欄

2 。當我打開該文件時,Excel給了我下面的警告:您嘗試打開的文件'excel.xls',格式與文件擴展名指定的格式不同,請確保文件未損壞並且來自可信來源打開文件。

  1. 在打開文件全部顯示在我的todaysappointmentsreport.export.phtml文件中的代碼

誰能告訴我,我要去哪裏錯了,因爲我需要得到這個工作。

我可以驗證查詢的工作原理和數據顯示在屏幕上我的todaysappointmentsreport.phtml文件中。我還可以驗證該組件是否安裝在梨以及它所依賴的OLE組件中。

我的控制器代碼

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;    
        } 

} 

我todaysappointmentsreport.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(); 
+0

任何人有任何想法? – Graham 2011-06-02 18:52:22

+0

我也有這個問題,然後我改爲PHPExcel(https://phpexcel.codeplex.com/)。這個庫在我看來比Spreadsheet_Excel_Writer好得多... – devOp 2012-08-20 14:11:56

回答

0

我正在爲我自己的項目工作一個類似的例子,所以如果我發現一個解決方案,我會用任何結果更新這個線程。

這裏有一篇關於contextSwitch視圖助手的文章(maltblue),它更深入地解釋了助手。

contextswitch view helper

我設法通過將頭控制器動作直接按如下方式導出爲CSV最終確定。

在我的行動

...

//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 $_csvFileNameFromAction = null; 

/** 
* Create the first part of the csv file name from the action name 
* @param <string> $actionName - name of the controller action for the report 
*/ 
public function __construct($actionName) 
{ 
    $this->_csvFileNameFromAction = $actionName; 
    $this->generateCsvHeader(); 
} 

/** 
* Method is called direct from the constructor 
* to centralise and make consistent the csv file header 
* so it maximises code re-use 
* @return null - just generate the csv header 
*/ 
public function generateCsvHeader() 
{ 
    $dateSuffix = date('d-m-Y', time()); 
    $csvFileName = $this->_csvFileNameFromAction.'_'.$dateSuffix; 

    header('Content-Type: text/x-csv; name="'.$csvFileName.'.csv"'); 
    header('Content-Disposition: inline; filename="'.$csvFileName.'.csv"'); 
    header('Pragma: public'); 
    header('Last-Modified: '.gmdate('D, d M Y H:i:s') . ' GMT'); 
    header('Cache-Control: no-store, no-cache, must-revalidate'); 
    header('Cache-Control: pre-check=0, post-check=0, max-age=0'); 
    header('Content-Transfer-Encoding: none'); 
} 

}

+0

我讀過那篇文章,非常好,任何輸入都非常感謝。由於時間限制,我爲我的項目做了一些工作,因爲我創建了一個包含查詢結果的xml文件,然後將其導入到excel中。 – Graham 2011-08-25 21:30:31

1

確保您的「todaysappointmentsreport.excel.phtml」視圖文件的內容包含在php的開始和結束標記中。

1
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(); 
}