2011-11-23 128 views
0

我試圖用Yii生成ms-word文檔。我很難做到這一點。我發現這個例子Generating ms-word,但我不能得到它的工作。Yii Framework生成ms-word文檔

View: 
echo CHtml::ajaxLink(
    'Generate Word', 
    CController::createUrl('Calculator/generateWord'), array(
     'type' => 'POST', 
    ), array('id'=>'gen_word') 
); 

Controller: 
$var = "hello"; 
$div = $this->renderPartial('graphs/print', array('var'=>$var), true); 
header("Pragma: no-cache"); // required 
header("Expires: 0"); 
header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); 
header("Cache-Control: private", false); // required for certain browsers 
header("Content-type: application/vnd.ms-word"); 
header("Content-Disposition: attachment; filename=\"test.doc"); 
header("Content-Transfer-Encoding: binary"); 
ob_clean(); 
flush(); 
echo $div; 

graphs/print: 
<table> 
    <tr> 
     <td>This is just s test</td> 
    </tr> 
    <tr> 
     <td><?php echo $var; ?></td> 
    </tr> 
</table> 

當我點擊「Generate Word」鏈接時,它什麼也不做。

+0

如果不是問題docx文件,您可以嘗試使用phpword來操作word docx文檔。這裏是如何使用:http://stackoverflow.com/a/23943396/2327332 – TotPeRo

回答

2

正確。這是必須完成的方式。問題是我正在做一個Ajax調用。相反,通過使用簡單的鏈接,沒有問題。

View: 
echo CHtml::link('Generate Word', array('Calculator/generateWord')); 

Controller: 
    public function actionGenerateWord() { 
    $var = "Hello World!"; 
    $div = $this->renderPartial('graphs/word', array('var'=>$var), true); 
    header("Pragma: no-cache"); 
    header("Expires: 0"); 
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); 
    header("Cache-Control: private", false); 
    header("Content-type: application/vnd.ms-word"); 
    header("Content-Disposition: attachment; filename=\"test.doc"); 
    header("Content-Transfer-Encoding: binary"); 
    ob_clean(); 
    flush(); 
    echo $div; 
    Yii::app()->end(); 
} 

Rendered view: 
<table> 
    <tr> 
     <td>This is just a test</td> 
    </tr> 
    <tr> 
     <td><?php echo $var; ?></td> 
    </tr> 
</table>