您现在的位置: 365建站网 > 365文章 > PHP中读取,写入和导出WORD文档的代码总结

PHP中读取,写入和导出WORD文档的代码总结

文章来源:365jz.com     点击数:965    更新时间:2017-08-29 11:18   参与评论
如果直接用FILE后者OPEN等函数读取WORD的话往往是乱码,原来要使用COM 这是我简单的一个读取并存储到新的WORD上的文件

一、先开启php.ini的COM,操作如下

1.

</>code

  1. extension=php_com_dotnet.dll

2.

</>code

  1. com.allow_dcom = true

二、开启之后就可以试下如下操作

1、建立一个指向新COM组件的索引

</>code

  1. $word = new COM("word.application") or die("Can't start Word!");

2、显示目前正在使用的Word的版本号

</>code

  1. echo "Loading Word, v. {$word->Version}";

3、把它的可见性设置为0(假),如果要使它在最前端打开,使用1(真)

</>code

  1. $word->Visible = 0;

4、打开一个文档

</>code

  1. $word->Documents->open(dirname(__FILE__)."/1.doc");

5、读取文档内容

</>code

  1. $test= $word->ActiveDocument->content->Text;

6、输出文档内容

</>code

  1. echo $test;

更多关于PHP中读取,写入和导出WORD文档的代码总结如下:

1.使用COM组件

</>code

  1. <? 
  2. // 建立一个指向新COM组件的索引 
  3. $word = new COM(”word.application”) or die(”Can't start Word!”); 
  4. // 显示目前正在使用的Word的版本号 
  5. //echo “Loading Word, v. {$word->Version}<br>”; 
  6. // 把它的可见性设置为0(假),如果要使它在最前端打开,使用1(真) 
  7. // to open the application in the forefront, use 1 (true) 
  8. //$word->Visible = 0; 
  9. //打?一个文档 
  10. $word->Documents->OPen(”d:\myweb\muban.doc”); 
  11. //读取文档内容 
  12. $test= $word->ActiveDocument->content->Text; 
  13. echo $test; 
  14. echo “<br>”; 
  15. //将文档中需要换的变量更换一下 
  16. $test=str_replace(”<{变量}>”,”这是变量”,$test); 
  17. echo $test; 
  18. $word->Documents->Add(); 
  19. // 在新文档中添加文字 
  20. $word->Selection->TypeText(”$test”); 
  21. //把文档保存在目录中 
  22. $word->Documents[1]->SaveAs(”d:/myweb/comtest.doc”); 
  23. // 关闭与COM组件之间的连接 
  24. $word->Quit(); 
  25. ?> 
2.比较简洁的一种方法,且可跨平台

以下为详细代码:

class.word.php

</>code

  1. <?php
  2. class Word{
  3. function start(){
  4. ob_start(); //打开输出控制缓冲
  5. echo '<html xmlns:o="urn:schemas-microsoft-com:office:office"';
  6. echo 'xmlns:w="urn:schemas-microsoft-com:office:word"';
  7. echo 'xmlns="http://www.w3.org/TR/REC-html40">';
  8. }
  9. function save($path){
  10. echo "</html>";
  11. $data=ob_get_contents(); //返回输出缓冲区的内容
  12. ob_end_clean(); //清空缓冲区并关闭输出缓冲
  13. $this->writeFile($path,$data); //将缓冲区内容写入word
  14. }
  15. function writeFile($fn,$data){
  16. $fp=fopen($fn,"wb+");
  17. fwrite($fp,$data);
  18. fclose($fp);
  19. }
  20. }

index.php

</>code

  1. <?php
  2. include("class.word.php");
  3. $word=new Word();
  4. $word->start();
  5. //以下内容会保存在WORD文件中,可以使用HTML标签
  6. ?>
  7. <h1>直接用php创建word文档</h1>
  8. 作者:axgle
  9. <hr size=1>
  10. <p>如果你打开data.doc,看到了这里的介绍,则说明word文档创建成功了。
  11. <p>
  12. 不论是在什么操作系统下,使用本方法都可以直接用PHP生成word文档。绝对不是吹牛!
  13. 就算是没有安装word,也能够生成word文件。
  14. 当然了,生成的word文件可以用word,wps或者其他软件打开。
  15. <p>
  16. <b>使用方法:</b>
  17. <br>
  18. 首先用$word->start()表示要生成word文件了。
  19. 然后你可以输出任何的HTML代码,不论是从文件读过来再写到这里,
  20. 还是直接在这里输出HTML,都没有关系。
  21. <p>等你输出完毕后,用$word->save($path)方法,其中$path是你想
  22. 生成的word文件的名称(可以给出完整的路径).当你使用了$word->save()
  23. 方法后,这后面的任何输出都和word文件没有关系了,也就是说word的生成
  24. 工作就完成了。之后就和你平常使用php的方式一样拉。随便你输出什么东西,
  25. 都直接在浏览器里输出,而不会写到word里面去。
  26. <p>这是本人想到的一个很有意思的方法,它的实现方法出人意料的简单,并且避免
  27. 了对windows环境的依赖。
  28. <br>哈哈,很有意思吧?享受它吧!
  29. <hr size=1>
  30. <?php
  31. //以上内容会保存在WORD文件中
  32. $word->save("data.doc");//保存word并且结束.
  33. //以下内容正常输出在页面文件中
  34. header("Content-type:text/html;charset=utf-8");
  35. echo 'data.doc生成成功,请到目录下查看<br>';
  36. ?>

3.通过baihui网API实现读取word文档并展示

可以 使用API 可以看看baihui.com 的写写应用 的API

申请一个 APPKEY 就能使用,你可以看看 ... 对免费版本有限制

比如 excel 支持,可以参考我这个 appkey是我申请的,可以使用吧 ...
保存成本地的一个html文件 打开后直接使用

word 的类似

</>code

  1. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  2. <html>
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  5. <title>测试百会格格远程API</title>
  6. </head>
  7. <body>
  8. <form action="http://gege.baihui.com/remotedoc.im?apikey=079c6475174c7a46351260ed35e54ecd&output=editor" target="_self" enctype="multipart/form-data" method="post">
  9. 上传文件: <input type="file" name="content" site="38"/>
  10. <input type="hidden" name="filename" value="my.xls,my.xlsx" />
  11. <input type="hidden" name="saveurl" value="http://vai.com" />
  12. <input type="hidden" name="id" value="21012145" />
  13. <input type="hidden" name="format" value="xlsx" />
  14. <input type="hidden" name="persistence" value="true" />
  15. <input type="submit" value="提交" />
  16. </form>
  17. </body>
  18. </html>


4.使用PHP导出Word文档的原理和实例
 

原理

 一般,有2种方法可以导出doc文档,一种是使用com,并且作为php的一个扩展库安装到服务器上,然后创建一个com,调用它的方法。安装过office的服务器可以调用一个叫word.application的com,可以生成word文档,不过这种方式我不推荐,因为执行效率比较低(我测试了一下,在执行代码的时候,服务器会真的去打开一个word客户端)。理想的com应该是没有界面的,在后台进行数据转换,这样效果会比较好,但是这些扩展一般需要收费。
第2种方法,就是用PHP将我们的doc文档内容直接写入一个后缀为doc的文件中即可。使用这种方法不需要依赖第三方扩展,而且执行效率较高。
 word本身的功能还是很强大的,它可以打开html格式的文件,并且能够保留格式,即使后缀为doc,它也能识别正常打开。这就为我们提供了方便。但是有一个问题,html格式的文件中的图片只有一个地址,真正的图片是保存在其他地方的,也就是说,如果将HTML格式写入doc中,那么doc中将不能包含图片。那我们如何创建包含图片的doc文档呢?我们可以使用和html很接近的mht格式。
mht格式和html很类似,只不过在mht格式中,外部链接进来的文件,比如图片、Javascript、CSS会被base64进行编码存储。因此,单个mht文件就可以保存一个网页中的所有资源,当然,相比html,它的尺寸也会比较大。
mht格式能被word识别吗?我将一个网页保存成mht,然后修改后缀名为doc,再用word打开,OK,word也可以识别mht文件,并且可以显示图片。
好了,既然doc可以识别mht,下面就是考虑如何将图片放入mht了。由于html代码中的图片的地址都是写在img标签的src属性中,因此,只要提取html代码中的src属性值,就可以获得图片地址。当然,有可能您获取到的是相对路径,没关系,加上URL的前缀,改成绝对路径就可以了。有了图片地址,我们就可以通过file_get_content函数获取到图片文件的具体内容,然后调用base64_encode函数将文件内容编码成base64编码,最后插入到mht文件的合适位置即可。
最后,我们有两种方法将文件发送给客户端,一种是先在服务器端生成一个doc文档,然后将这个doc文档的地址记录下来,最后,通过header("location:xx.doc");就可以让客户端下载这个doc。还有一种是直接发送html请求,修改HTML协议的header部分,将它的content-type设置为application/doc,将content-disposition设置为attachment,后面跟上文件名,发送完html协议以后,直接将文件内容发送给客户端,也可以让客户端下载到这个doc文档。

实现

通过以上的原理介绍,相信大家应该对实现的过程有个初步的了解了,下面我给出一个导出函数,这个函数可以将HTML代码导出成一个mht文档,参数有3个,其中后2个为可选参数
content:要转换的HTML代码
absolutePath: 如果HTML代码中的图片地址都是相对路径,那么这个参数就是HTML代码中缺少的绝对路径。
isEraseLink:是否去掉HTML代码中的超链接
返回值为mht的文件内容,您可以通过file_put_content将它保存成后缀名为doc的文件
这个函数的主要功能其实就是分析HTML代码中的所有图片地址,并且依次下载下来。获取到了图片的内容以后,调用MhtFileMaker类,将图片添加到mht文件中。具体的添加细节,封装在MhtFileMaker类中了。

 

</>code

  1. /**
  2.  * 根据HTML代码获取word文档内容
  3.  * 创建一个本质为mht的文档,该函数会分析文件内容并从远程下载页面中的图片资源
  4.  * 该函数依赖于类MhtFileMaker
  5.  * 该函数会分析img标签,提取src的属性值。但是,src的属性值必须被引号包围,否则不能提取
  6.  *
  7.  * @param string $content HTML内容
  8.  * @param string $absolutePath 网页的绝对路径。如果HTML内容里的图片路径为相对路径,那么就需要填写这个参数,来让该函数自动填补成绝对路径。这个参数最后需要以/结束
  9.  * @param bool $isEraseLink 是否去掉HTML内容中的链接
  10. * by www.365jz.com
  11.  */
  12. function getWordDocument( $content , $absolutePath = "" , $isEraseLink = true )
  13. {
  14.     $mht = new MhtFileMaker();
  15.     if ($isEraseLink)
  16.         $content = preg_replace('/<a\s*.*?\s*>(\s*.*?\s*)<\/a>/i' , '$1' , $content);   //去掉链接
  17. $images = array();
  18.     $files = array();
  19.     $matches = array();
  20.     //这个算法要求src后的属性值必须使用引号括起来
  21.     if ( preg_match_all('/<img[.\n]*?src\s*?=\s*?[\"\'](.*?)[\"\'](.*?)\/>/i',$content ,$matches ) )
  22.     {
  23.         $arrPath = $matches[1];
  24.         for ( $i=0;$i<count($arrPath);$i++)
  25.         {
  26.             $path = $arrPath[$i];
  27.             $imgPath = trim( $path );
  28.             if ( $imgPath != "" )
  29.             {
  30.                 $files[] = $imgPath;
  31.                 if( substr($imgPath,0,7) == 'http://')
  32.                 {
  33.                     //绝对链接,不加前缀
  34.                 }
  35.                 else
  36.                 {
  37.                     $imgPath = $absolutePath.$imgPath;
  38.                 }
  39.                 $images[] = $imgPath;
  40.             }
  41.         }
  42.     }
  43.     $mht->AddContents("tmp.html",$mht->GetMimeType("tmp.html"),$content);
  44.     for ( $i=0;$i<count($images);$i++)
  45.     {
  46.         $image = $images[$i];
  47.         if ( @fopen($image , 'r') )
  48.         {
  49.             $imgcontent = @file_get_contents( $image );
  50.             if ( $content )
  51.                 $mht->AddContents($files[$i],$mht->GetMimeType($image),$imgcontent);
  52.         }
  53.         else
  54.         {
  55.             echo "file:".$image." not exist!<br />";
  56.         }
  57.     }
  58.     return $mht->GetFile();
  59. }

 

 

 

使用方法:

 

</>code

  1. $fileContent = getWordDocument($content,"https://www.365jz.com/Music/etc/");
  2. $fp = fopen("test.doc", 'w');
  3. fwrite($fp, $fileContent);
  4. fclose($fp);

 

其中,$content变量应该是HTML源代码,后面的链接应该是能填补HTML代码中图片相对路径的URL地址
注意,在使用这个函数之前,您需要先包含类MhtFileMaker,这个类可以帮助我们生成Mht文档。

 

</>code

  1. <?php
  2. /***********************************************************************
  3. Class:        Mht File Maker
  4. Version:      1.2 beta
  5. Author:       Wudi <wudicgi@yahoo.de>
  6. Description:  The class can make .mht file.
  7. ***********************************************************************/
  8. class MhtFileMaker{
  9.     var $config = array();
  10.     var $headers = array();
  11.     var $headers_exists = array();
  12.     var $files = array();
  13.     var $boundary;
  14.     var $dir_base;
  15.     var $page_first;
  16.     function MhtFile($config = array()){
  17.     }
  18.     function SetHeader($header){
  19.         $this->headers[] = $header;
  20.         $key = strtolower(substr($header, 0, strpos($header, ':')));
  21.         $this->headers_exists[$key] = TRUE;
  22.     }
  23.     function SetFrom($from){
  24.         $this->SetHeader("From: $from");
  25.     }
  26.     function SetSubject($subject){
  27.         $this->SetHeader("Subject: $subject");
  28.     }
  29.     function SetDate($date = NULL, $istimestamp = FALSE){
  30.         if ($date == NULL) {
  31.             $date = time();
  32.         }
  33.         if ($istimestamp == TRUE) {
  34.             $date = date('D, d M Y H:i:s O', $date);
  35.         }
  36.         $this->SetHeader("Date: $date");
  37.     }
  38.     function SetBoundary($boundary = NULL){
  39.         if ($boundary == NULL) {
  40.             $this->boundary = '--' . strtoupper(md5(mt_rand())) . '_MULTIPART_MIXED';
  41.         } else {
  42.             $this->boundary = $boundary;
  43.         }
  44.     }
  45.     function SetBaseDir($dir){
  46.         $this->dir_base = str_replace("\\", "/", realpath($dir));
  47.     }
  48.     function SetFirstPage($filename){
  49.         $this->page_first = str_replace("\\", "/", realpath("{$this->dir_base}/$filename"));
  50.     }
  51.     function AutoAddFiles(){
  52.         if (!isset($this->page_first)) {
  53.             exit ('Not set the first page.');
  54.         }
  55.         $filepath = str_replace($this->dir_base, '', $this->page_first);
  56.         $filepath = 'http://mhtfile' . $filepath;
  57.         $this->AddFile($this->page_first, $filepath, NULL);
  58.         $this->AddDir($this->dir_base);
  59.     }
  60.     function AddDir($dir){
  61.         $handle_dir = opendir($dir);
  62.         while ($filename = readdir($handle_dir)) {
  63.             if (($filename!='.') && ($filename!='..') && ("$dir/$filename"!=$this->page_first)) {
  64.                 if (is_dir("$dir/$filename")) {
  65.                     $this->AddDir("$dir/$filename");
  66.                 } elseif (is_file("$dir/$filename")) {
  67.                     $filepath = str_replace($this->dir_base, '', "$dir/$filename");
  68.                     $filepath = 'http://mhtfile' . $filepath;
  69.                     $this->AddFile("$dir/$filename", $filepath, NULL);
  70.                 }
  71.             }
  72.         }
  73.         closedir($handle_dir);
  74.     }
  75.     function AddFile($filename, $filepath = NULL, $encoding = NULL){
  76.         if ($filepath == NULL) {
  77.             $filepath = $filename;
  78.         }
  79.         $mimetype = $this->GetMimeType($filename);
  80.         $filecont = file_get_contents($filename);
  81.         $this->AddContents($filepath, $mimetype, $filecont, $encoding);
  82.     }
  83.     function AddContents($filepath, $mimetype, $filecont, $encoding = NULL){
  84.         if ($encoding == NULL) {
  85.             $filecont = chunk_split(base64_encode($filecont), 76);
  86.             $encoding = 'base64';
  87.         }
  88.         $this->files[] = array('filepath' => $filepath,
  89.                                'mimetype' => $mimetype,
  90.                                'filecont' => $filecont,
  91.                                'encoding' => $encoding);
  92.     }
  93.     function CheckHeaders(){
  94.         if (!array_key_exists('date', $this->headers_exists)) {
  95.             $this->SetDate(NULL, TRUE);
  96.         }
  97.         if ($this->boundary == NULL) {
  98.             $this->SetBoundary();
  99.         }
  100.     }
  101.     function CheckFiles(){
  102.         if (count($this->files) == 0) {
  103.             return FALSE;
  104.         } else {
  105.             return TRUE;
  106.         }
  107.     }
  108.     function GetFile(){
  109.         $this->CheckHeaders();
  110.         if (!$this->CheckFiles()) {
  111.             exit ('No file was added.');
  112.         } //www.365jz.com
  113.         $contents = implode("\r\n", $this->headers);
  114.         $contents .= "\r\n";
  115.         $contents .= "MIME-Version: 1.0\r\n";
  116.         $contents .= "Content-Type: multipart/related;\r\n";
  117.         $contents .= "\tboundary=\"{$this->boundary}\";\r\n";
  118.         $contents .= "\ttype=\"" . $this->files[0]['mimetype'] . "\"\r\n";
  119.         $contents .= "X-MimeOLE: Produced By Mht File Maker v1.0 beta\r\n";
  120.         $contents .= "\r\n";
  121.         $contents .= "This is a multi-part message in MIME format.\r\n";
  122.         $contents .= "\r\n";
  123.         foreach ($this->files as $file) {
  124.             $contents .= "--{$this->boundary}\r\n";
  125.             $contents .= "Content-Type: $file[mimetype]\r\n";
  126.             $contents .= "Content-Transfer-Encoding: $file[encoding]\r\n";
  127.             $contents .= "Content-Location: $file[filepath]\r\n";
  128.             $contents .= "\r\n";
  129.             $contents .= $file['filecont'];
  130.             $contents .= "\r\n";
  131.         }
  132.         $contents .= "--{$this->boundary}--\r\n";
  133.         return $contents;
  134.     }
  135.     function MakeFile($filename){
  136.         $contents = $this->GetFile();
  137.         $fp = fopen($filename, 'w');
  138.         fwrite($fp, $contents);
  139.         fclose($fp);
  140.     }
  141.     function GetMimeType($filename){
  142.         $pathinfo = pathinfo($filename);
  143.         switch ($pathinfo['extension']) {
  144.             case 'htm': $mimetype = 'text/html'; break;
  145.             case 'html': $mimetype = 'text/html'; break;
  146.             case 'txt': $mimetype = 'text/plain'; break;
  147.             case 'cgi': $mimetype = 'text/plain'; break;
  148.             case 'php': $mimetype = 'text/plain'; break;
  149.             case 'css': $mimetype = 'text/css'; break;
  150.             case 'jpg': $mimetype = 'image/jpeg'; break;
  151.             case 'jpeg': $mimetype = 'image/jpeg'; break;
  152.             case 'jpe': $mimetype = 'image/jpeg'; break;
  153.             case 'gif': $mimetype = 'image/gif'; break;
  154.             case 'png': $mimetype = 'image/png'; break;
  155.             default: $mimetype = 'application/octet-stream'; break;
  156.         }
  157.         return $mimetype;
  158.     }
  159. }
  160. ?>

 

 

 

上面讨论了通过mht文件,来实现PHP导出doc格式的。这种方法可以解决一个难题,就是使导出的doc文件中包含图片,当然,如果您要包含更多的内容,比如CSS样式表,只需要用正则表达式分析HTML代码中的link标签,提取css样式文件的地址,然后读取并编码成base64,最后加入到mht文件中就可以了。


以上所述就是本文的全部内容了,希望大家能够喜欢。



如对本文有疑问,请提交到交流论坛,广大热心网友会为你解答!! 点击进入论坛

发表评论 (965人查看0条评论)
请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
昵称:
最新评论
------分隔线----------------------------

快速入口

· 365软件
· 杰创官网
· 建站工具
· 网站大全

其它栏目

· 建站教程
· 365学习

业务咨询

· 技术支持
· 服务时间:9:00-18:00
365建站网二维码

Powered by 365建站网 RSS地图 HTML地图

copyright © 2013-2024 版权所有 鄂ICP备17013400号