首页 > 开发 > PHP > 正文

php在程序中将网页生成word文档并提供下载的代码

2024-05-04 22:28:05
字体:
来源:转载
供稿:网友
在这篇文章中主要解决两个问题:

1:在php中如何把html中的内容生成到word文档中
2:php把html中的内容生成到word文档中时,不居中显示问题,即会默认按照web视图进行显示。
3:php把html中的内容生成到word文档中时,相关样式不兼容问题

正文:
代码如下:
echo '<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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<xml><w:WordDocument><w:View>Print</w:View></xml>
<script src="includes/js/ztree/js/jquery-1.4.4.min.js" type="text/javascript"></script>
</head>';
echo '<body><table class="table_dayin">
<caption class="table_caption">';
echo "数字化教学系统电子备课稿<br>
<span>学科 <em style="border-bottom: 1px solid #545454;">语文</em>学校 <em style="border-bottom: 1px solid #545454;">实验中学</em></span>
</caption>";
echo '</table></body></html>';
ob_start(); //打开缓冲区
header("Cache-Control: public");
Header("Content-type: application/octet-stream");
Header("Accept-Ranges: bytes");
if (strpos($_SERVER["HTTP_USER_AGENT"],'MSIE')) {
header('Content-Disposition: attachment; filename=test.doc');
}else if (strpos($_SERVER["HTTP_USER_AGENT"],'Firefox')) {
Header('Content-Disposition: attachment; filename=test.doc');
} else {
header('Content-Disposition: attachment; filename=test.doc');
}
header("Pragma:no-cache");
header("Expires:0");
ob_end_flush();//输出全部内容到浏览器

注:以上代码部分提供了在php程序文件中生成内容到word文档中并提供下载功能。
针对第2个问题,下载到本地的word文档打开后显示默认按照web视图进行显示的问题:如下图:
按照默认web视图显示:

 

如果按照正常的页面视图进行显示的话,需要在头部添加一行xml标示进行设置(蓝色代码部分):<xml><w:WordDocument><w:View>Print</w:View></xml>,添加后下载到本地的word文档打开后显示如下图:

 

针对第三个问题就是有一些样式不兼容问题,比如顶部的大标题下面的相关属性的下划线标注显示:

  我们在html中的样式中添加了border-bottom: 1px solid #545454;这个样式(蓝色代码部分),即:<em style="border-bottom: 1px solid #545454;">,但是下划线还是没有显示,因为在word中不识别。如下图:

 

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表