您的位置 首页 php

PHP完美生成word文档,可加入html元素

PHP生成word文档,网上有很多方法,有调用COM组件生成的,有安装PHP扩展生成的,也有引用第三方类库,如phpword生成的。以下为最简洁的两种方法,无须安装其他,只要你安装了php环境便可以直接生成。

<?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)){

ret urn ;

}

$content='<html

xmlns:o=”urn:schemas-microsoft-com:office:office”

xmlns:w=”urn:schemas-microsoft-com:office:word”

xmlns=””>

<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=””

xmlns=””>’;

$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’);

运行后的效果图

PHP生成word文档

PHP生成word文档

文章来源:智云一二三科技

文章标题:PHP完美生成word文档,可加入html元素

文章地址:https://www.zhihuclub.com/149585.shtml

关于作者: 智云科技

热门文章

网站地图