在网上找了很多php生成word的代码,感觉都不适合cakephp,所以参照了一下CakeEmail,照着写了一个根据模板,生成word文档。
首先创建一个conponent,方便其他controller调用
地址:appControllerComponentToolsComponent.php
<?php
App::uses ( 'Component', 'Controller' );
class ToolsComponent extends Component {
protected $_viewVars = array ();
protected $_helpers = array ();
var $charset = "utf-8";
public function __construct(ComponentCollection $collection, $settings = array()) {
parent::__construct ( $collection, $settings );
}
/**
* 根据模板生成world文档
*/
public function makeWordByTemplate($data = array(), $template = "students") {
$View = new View ();
// $layout = "default";
$layout = null;
$this->_viewVars = array (
"title_for_layout" => "学生管理"
);
if (! empty ( $data )) {
$this->_viewVars = array_merge ( $this->_viewVars, $data );
}
$View->viewVars = $this->_viewVars;
$View->helpers = $this->_helpers;
$View->hasRendered = false;
$View->viewPath = $View->layoutPath = 'Tools';
$render = $View->render ( $template, $layout );
$render = str_replace ( array (
"
",
"
"
), "
", $render );
return $render;
}
}
创建工具类的默认布局文件appViewLayoutsToolsdefault.ctp
内容:
<html xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:w="urn:schemas-microsoft-com:office:word" xmlns:m="http://schemas.microsoft.com/office/2004/12/omml"
xmlns="http://www.w3.org/TR/REC-html40">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title><?php echo $title_for_layout;?></title>
<style>
@font-face {
font-family:"Times New Roman";
}
@font-face {
font-family:"宋体";
}
@font-face {
font-family:"Arial";
}
table{border-collapse:collapse;border-color:#000;}
td{ border-color:#000; padding:10px 5px; vertical-align:middle;}
h1{ text-align:center}
.f_ri{ text-align:right;}
table {
width: 100%;
background-color: transparent;
border-collapse: collapse;
border-spacing: 0;
}
</style>
<!--[if gte mso 9]><xml><w:WordDocument><w:View>Print</w:View><w:TrackMoves>false</w:TrackMoves><w:TrackFormatting/><w:ValidateAgainstSchemas/><w:SaveIfXMLInvalid>false</w:SaveIfXMLInvalid><w:IgnoreMixedContent>false</w:IgnoreMixedContent><w:AlwaysShowPlaceholderText>false</w:AlwaysShowPlaceholderText><w:DoNotPromoteQF/><w:LidThemeOther>EN-US</w:LidThemeOther><w:LidThemeAsian>ZH-CN</w:LidThemeAsian><w:LidThemeComplexScript>X-NONE</w:LidThemeComplexScript><w:Compatibility><w:BreakWrappedTables/><w:SnapToGridInCell/><w:WrapTextWithPunct/><w:UseAsianBreakRules/><w:DontGrowAutofit/><w:SplitPgBreakAndParaMark/><w:DontVertAlignCellWithSp/><w:DontBreakConstrainedForcedTables/><w:DontVertAlignInTxbx/><w:Word11KerningPairs/><w:CachedColBalance/><w:UseFELayout/></w:Compatibility><w:BrowserLevel>MicrosoftInternetExplorer4</w:BrowserLevel><m:mathPr><m:mathFont m:val="Cambria Math"/><m:brkBin m:val="before"/><m:brkBinSub m:val="--"/><m:smallFrac m:val="off"/><m:dispDef/><m:lMargin m:val="0"/> <m:rMargin m:val="0"/><m:defJc m:val="centerGroup"/><m:wrapIndent m:val="1440"/><m:intLim m:val="subSup"/><m:naryLim m:val="undOvr"/></m:mathPr></w:WordDocument></xml><![endif]-->
</head>
<body>
<?php echo $content_for_layout;?>
</body>
</html>
再创建模板文件,appViewToolsstudents.ctp
内容:
<table border="1" cellpadding="0" cellspacing="0" >
<tr> <th>姓名</th>
<th>学号</th> <th>密码</th>
</tr>
<?php if(!empty($students)){foreach($students as $k=>$v){?>
<tr>
<td><?php echo $v["username"]?></td>
<td><?php echo $v["userId"]?></td>
<td><?php echo $v["pwd"]?></td>
</tr>
<?php }}?>
</table>
在controller中,引入这个文件
var $components = array ("Tools");
创建一个action,专门用来生成并下载这个文件
public function download() {
$id = ! empty ( $_REQUEST ["cid"] ) ? intval ( $_REQUEST ["cid"] ) : 0;
// 查询学生列表
$student = $this->getStudentById ( $id );
$data = array ( "students" => $student
);
$word = $this->Tools->makeWordByTemplate ( $data, "students" );//传入数据和模板名称
// 保存到文件
$student_file_path_prev = TMP . "cache" . DS;
$sf_name = time() . "_file" . ".doc";
$sf_name2 = "下载测试文件.doc";
$student_file_path = $student_file_path_prev . $sf_name;
$fp = fopen ( $student_file_path, 'w' ); // 打开生成的文档
fwrite ( $fp, $word ); // 写入包保存文件
fclose ( $fp );
$params = array (
'id' => $sf_name,
'name' => $sf_name2,
'download' => true,
'path' => $student_file_path_prev
);//下载参数
$this->viewClass = 'Media';
$this->set ( $params );
}
现在访问:localhost/download 会下载一个“下载测试文件.doc”,同时在缓存目录下,生成一个时间戳的doc文件