查看了PHP手册中关于 COM 的用法, 发现调用MS的 word / excel 很容易, 但其中有一些问题讲的不细, 但网上没有更多的资料, 写一些来共享, 抛砖引玉.
<?php
// starting word
$word = new COM("word.application") or die("Unable to instantiate Word"); echo "Loaded Word, version {$word->Version}<br />";
//bring it to front
$word->Visible = 1;
//open an empty document
$word->Documents->Add();
//如果是 UTF-8 编码要转码
$str = iconv("utf-8","gbk","邀月同宿青山深处");
//do some weird stuff
$word->Selection->TypeText($str); $word->ActiveDocument->SaveAs("d:/demo/test.doc");
//closing word
$word->Quit();
//free the object
$word = null; ?>
|
以上代码中有两点要注意: 1. 如果写入word文件中的字符有中文时要注意转码.如不转码则报错: Warning: Unknown: Could not convert string to unicode: `在多字节的目标代码页中,没有此 Unicode 字符可以映射到的字符。 2. 保存文件时注意路径, 如不写完整则存入系统默认路径下: C:\WINDOWS\system32\config\systemprofile\My documents\ |
|