Chinaunix

标题: php 中利用 COM 调用 word 文档 [打印本页]

作者: shenyl123    时间: 2009-11-07 12:17
标题: php 中利用 COM 调用 word 文档

                查看了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}
";
//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\
               
               

本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u3/104997/showart_2088547.html




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2