PHP生成word文檔碳胳,網(wǎng)上有很多方法勇蝙,有調(diào)用COM組件生成的,有安裝PHP擴(kuò)展生成的挨约,也有引用第三方類庫味混,如phpword生成的。以下為最簡潔的兩種方法诫惭,無須安裝其他翁锡,只要你安裝了php環(huán)境便可以直接生成。
<?php
header("Content-type:text/html;charset=utf-8");
/**
* @desc 方法一夕土、生成word文檔
* @param $content
* @param string $fileName
*/
function createWord($content='',$fileName='new_file.doc'){
if(empty($content)){
return;
}
$content='<html
xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:w="urn:schemas-microsoft-com:office:word"
xmlns="http://www.w3.org/TR/REC-html40">
<meta charset="UTF-8" />'.$content.'</html>';
if(empty($fileName)){
$fileName=date('YmdHis').'.doc';
}
$fp=fopen($fileName,'wb');
fwrite($fp,$content);
fclose($fp);
}
$str = '<h1 style="color:red;">我是h1</h1><h2>我是h2</h2>';
createWord($str);
/**
* @desc 方法二馆衔、生成word文檔并下載
* @param $content
* @param string $fileName
*/
function downloadWord($content, $fileName='new_file.doc'){
if(empty($content)){
return;
}
header("Cache-Control: no-cache, must-revalidate");
header("Pragma: no-cache");
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=$fileName");
$html = '<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">';
$html .= '<head><meta charset="UTF-8" /></head>';
echo $html . '<body>'.$content .'</body></html>';
}
$str = '<h4>表頭:</h4>
<table border="1">
<tr>
<th>姓名</th>
<th>電話</th>
<th>電話</th>
</tr>
<tr>
<td>Bill Gates</td>
<td>555 77 854</td>
<td>555 77 855</td>
</tr>
</table>';
downloadWord($str, 'abc.doc');
運(yùn)行后的效果圖
轉(zhuǎn)載請標(biāo)明原文鏈接: http://www.reibang.com/p/3a59904c6898
更多精彩請?jiān)L問個(gè)人博客:https://www.whmblog.cn/