C#生成注册COM+,可由PHP调用【自己解决 科普+散分】

APM60- APM60- 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
先交代下背景。需要实现类似邮箱附件预览的功能,不能把文档传到第3放网站。服务器后台PHP,系统XP。

我就想用C#通过调用office组件来实现文档转换,再由PHP来触发。
参考了这上面的资料http://it.chinawin.net/softwaredev/article-1b87e.html

using System;
using System.Runtime.InteropServices;namespace ComLibrary {
[Guid("2BF6AD68-C374-4877-AB19-B523AC1148AD")]
public interface ITest {
[DispId(0)]
string GetGuid();
[DispId(1)]
string About();
[DispId(2)]
int Add(int a, int b);
} [Guid("585AC64C-53ED-4be8-A4F7-90397D676443")]
public class Test : ITest {
public string GetGuid() {
return System.Guid.NewGuid().ToString();
} public string About() {
return "Hello higkoo !";
} public int Add(int a, int b) {
return a + b; }
}

生成dll并注册。
注册方式:regsvr32 ComLibrary.dll /s

<?php
$c= new COM("ComLibrary.Test");
echo $c->About();
?>

PHP调用,以上都正常。
本机PHP环境为XMAPP。

然后我再加上文档转换的代码
我用的office2007,其中
using MSWord = Microsoft.Office.Interop.Word;

try
{
MSWord.ApplicationClass word = new MSWord.ApplicationClass();
Type wordType = word.GetType();
MSWord.Documents docs = word.Documents;
Type docsType = docs.GetType();
strMsg += "-打开文档" + docsType.ToString();
MSWord.Document doc = (MSWord.Document)docsType.InvokeMember("Open", System.Reflection.BindingFlags.InvokeMethod, null, docs, new Object[] { wordFilePath, true, true });
Type docType = doc.GetType();
strMsg += "-另存文档" + docType.ToString();
docType.InvokeMember("SaveAs", System.Reflection.BindingFlags.InvokeMethod,
null, doc, new object[] { htmlFilePath, MSWord.WdSaveFormat.wdFormatFilteredHTML });
strMsg += "-退出WORD";
wordType.InvokeMember("Quit", System.Reflection.BindingFlags.InvokeMethod, null, word, null);
strMsg += "-转换成功";
}
catch (Exception ex)
{
strMsg += @"--错误信息:" + ex.Message;
}
finally
{
//最后关闭打开的winword 进程
Process[] myProcesses = Process.GetProcessesByName("WINWORD");
foreach (Process myProcess in myProcesses)
{
myProcess.Kill();
}
}
// 记录日志
strMsg += "--文档路径:" + wordFilePath + "--时间:" +DateTime.Now.ToString() + "\r\n";
using (var writer = new StreamWriter(logFilePath, true, Encoding.UTF8))
{
writer.Write(strMsg);
}

生成的dll在被其他winform程序调用时,能够正常转换文档。

但是用PHP调用时,就会出错。
在保存的日志里发现,在打开文档这一步出错了。

怀疑的几个可能出现错误的原因:
1、调用该dll再引用office组件时出错。但如果是这样的话,应该在创建MSWord.ApplicationClass实例时就会出错才对。
2、word文件路径错误。但是输出日志里的word文件路径是能够找到的。
3、文件读写权限。但是日志文件能够正常写入,估计也不是权限的问题。
4、生成dll的时候犯了某些基础性的错误。头一次这么用,确实不熟悉。
实在没什么头绪了。

我还想到了一个方法,就是新建一个exe实现文档转换。
上面的dll只调用这个exe。这样的话,dll需要知道exe文件具体路径才能正确调用。
最好是一个dll能够实现,最后再考虑这个方法。

恳请各位指点一下,如何才能实现这个功能?


...全文
评论 14
收藏 已收藏
分享
返回顶部
APM60-
C# 111,129 成员 642,538 内容