使用 PHP 导出到 MS-Word
我想在 Windows 和 Linux 操作系统上使用 PHP 将数据导出到 MS Word 文件。我写了以下代码。
header("Content-type: application/vnd.ms-word");
header("Content-Disposition: attachment;Filename=document_name.doc");
echo "<html>";
echo "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=Windows-1252\">";
echo "<body>";
echo '<table cellpadding="0" cellspacing="0" border="0" width="100%">';
echo '<tr><td>test data</td></tr>';
echo '</table>';
echo "</body>";
echo "</html>";
使用 MS Office 2007 打开时,我的 MS Word 文件正确且没有表格边框。但是,如果我使用 MS Office 2003 打开它,则我的 MS Word 文件的表格边框 =“1”。
我该如何解决这个问题?
I want to export data to MS Word file using PHP on Windows and Linux operating system. I have written following code.
header("Content-type: application/vnd.ms-word");
header("Content-Disposition: attachment;Filename=document_name.doc");
echo "<html>";
echo "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=Windows-1252\">";
echo "<body>";
echo '<table cellpadding="0" cellspacing="0" border="0" width="100%">';
echo '<tr><td>test data</td></tr>';
echo '</table>';
echo "</body>";
echo "</html>";
I have the MS Word file properly without table border when opened with MS Office 2007. But, if I open it with MS Office 2003 then I have the MS Word file with table border = '1'.
How can I fix this problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您通过 HTTP 标头指示您正在发送 Word 文档(mime 类型 applciation/vnd-ms-word),但实际上您正在将 HTML 输出到该文档中。如果您在文本编辑器(记事本是一个合理的选择)中打开生成的 .doc 文件,您将看到它实际上是一个名为 .doc 的 HTML 文件。 Word 可以解析此内容,但格式化的可能性非常有限 - 它无法理解适当的 Web 浏览器可以理解的所有内容。
相反,您需要将输出实际转换为 Word 文档格式。我不建议手动执行此操作。如果您在 Windows 上运行,则可以使用 COM 创建文档。在 Linux 上你就不走运了,需要使用第三方库。查看 Zend LiveDocx 框架: http://www.phplivedocx.org /articles/phplivedocx 简介/
You are indicating via HTTP headers that you're sending a word document (mime type applciation/vnd-ms-word), however you're actually outputting HTML into that document. If you open the resulting .doc file in a text editor (notepad is a reasonable choice), you'll see that it's actually an HTML file named as .doc. Word can parse this, but the possibilities for formatting are very limited - it doesn't understand everything that a proper web browser would understand.
Instead, you would need to actually convert your output to word document format. I wouldn't recommend doing this by hand. If you're running on Windows, you can use COM to create the document. On linux you're out of luck and would need to use a third-party library. Have a look at the Zend LiveDocx Framework: http://www.phplivedocx.org/articles/brief-introduction-to-phplivedocx/