学习使用php实现生成word文档的代码
纯HTML格式写入word
利用ob_start把html页面先存储起来(解决一下页面多个header问题,可以批量生成),然后在写入doc文档内容利用
<?php
class word
{
function start()
{
ob_start();
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">';
}
function save($path)
{
echo "</html>";
$data = ob_get_contents();
ob_end_clean();
$this->wirtefile($path, $data);
}
function wirtefile($fn, $data)
{
$fp = fopen($fn, "wb");
fwrite($fp, $data);
fclose($fp);
}
}
$html = '
<style>
@font-face{
font-family:"Times New Roman";
}
@font-face{
font-family:"宋体";
}
@font-face{
font-family:"Wingdings";
}
p.MsoNormal{
mso-style-name:正文;
mso-style-parent:"";
margin:0pt;
margin-bottom:.0001pt;
font-family:\'Times New Roman\';
font-size:12.0000pt;
}
@page{mso-page-border-surround-header:no;
mso-page-border-surround-footer:no;}@page Section0{
margin-top:72.0000pt;
margin-bottom:72.0000pt;
margin-left:90.0000pt;
margin-right:90.0000pt;
size:612.0000pt 792.0000pt;
layout-grid:18.0000pt;
mso-header-margin:35.4000pt;
mso-footer-margin:35.4000pt;
}
div.Section0{page:Section0;}</style></head><body style="tab-interval:36pt;" ><!--StartFragment--><div class="Section0" style="layout-grid:18.0000pt;" ><p class=MsoNormal align=center style="margin-bottom:20.0000pt;text-indent:8.0000pt;mso-pagination:none;
text-align:center;" ><b style="mso-bidi-font-weight:normal" ><span style="mso-spacerun:\'yes\';font-family:\'Times New Roman\';mso-ansi-font-weight:bold;
font-size:16.0000pt;" ><font face="Times New Roman" >语文考试题</font></span></b><span style="mso-spacerun:\'yes\';font-family:\'Times New Roman\';font-size:12.0000pt;" ><o:p></o:p></span></p><p class=MsoNormal ><b style="mso-bidi-font-weight:normal" ><span style="mso-spacerun:\'yes\';font-family:\'Times New ;mso-ansi-font-weight:bold;
Roman\';color:rgb(140,140,140);" ><o:p></o:p></span></p><p class=MsoNormal ><span style="mso-spacerun:\'yes\';font-family:\'Times New Roman\';font-size:12.0000pt;" ><o:p> </o:p></span></p><p class=MsoNormal ><span style="mso-spacerun:\'yes\';font-family:\'Times New Roman\';font-size:12.0000pt;" ><o:p> </o:p></span></p></div><!--EndFragment--></body></html>
';
//批量生成 可以不必要批量生成
for ($i = 1; $i <= 3; $i++) {
$word = new word();
$word->start();
$wordname = iconv("UTF-8", "GBK//IGNORE", '哎呀www.qipa250.com_' . $i . "_奇葩.doc");
echo $html;
$word->save($wordname);
ob_flush();//每次执行前刷新缓存
flush();
}
?>
打开生成的word文档,效果图如下: