或许上传word文件,然后转换成HTML这个标题在百度上一搜一堆

悲剧的是,我试了N多,却没有一个可以运行成功(我用.Net 4环境)

可能比较大的原因是自己比较菜吧…

 

网上的例子(其实都是一个样的代码,已经拷贝得不知道原作者是谁了)

//创建word实例
Microsoft.Office.Interop.Word.ApplicationClass word = new Microsoft.Office.Interop.Word.ApplicationClass();
Type wordType = word.GetType();
//文档s
Microsoft.Office.Interop.Word.Documents docs = word.Documents;
Type docsType = docs.GetType();
//打开文档
Microsoft.Office.Interop.Word.Document doc = (Document)docsType.InvokeMember("Open",System.Reflection.BindingFlags.InvokeMethod, null, docs, new Object[] {fileName, true, true});
Type doctype = doc.GetType();
//另存为
doctype.InvokeMember("SaveAs", System.Reflection.BindingFlags.InvokeMethod, null, doc,new object[] {savefilename, WdSaveFormat.wdFormatHTML}); //另存为Html格式
//关闭
wordType.InvokeMember("Quit", System.Reflection.BindingFlags.InvokeMethod, null, word, null);

 

 

首先就是dll的问题,很多都说是 Microsoft Office 11/12 Object Lib 这个COM组件

可是引入才发现…

根本没有Word这个命名空间…

 

慢慢找才发现,其实有Microsoft Word这个COM的…

 

dll过了,但是这样写,语法上不报错,但是已编译就有问题了

 

'Microsoft.Office.Interop.Word.ApplicationClass' does not contain a definition for 'Documents' and no extension method 'Documents' accepting a first argument of type 'Microsoft.Office.Interop.Word.ApplicationClass' could be found (are you missing a using directive or an assembly reference?)

 

可能自己以前使用UnManaged的代码经历太少的缘故,不懂为什么命名引入了命名空间,但是仍然找不到…

 

过了一下才缓过来,ApplicationClass是类,在这里却不能使用,必须使用接口

Application正是 ApplicationClass的接口…

 

改为

Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();

 

这样才能编译通过

 

中间的代码都没什么难度,都是先取得对应的类型,反射调用其中的方法即可

 

最后,运行效果不太理想

转换出的HTML比较悲剧…

 

自己摸索一下,发现这个和另存为的格式有关

其中HTML有2种

 

一种是 wdFormatHTML ,这种有点头疼,转换出来的标签,很多都是Word自身的,而并不是HTML标准的。

另一种是 wdFormatFilteredHTML,这个表现出的效果才比较满意,标签都是HTML标准标签。

 

本以为完事了,结果集成到上传代码的时候出了问题

 

逻辑是:

转换出HTML后,直接读取存入数据库,然后删除转换出的HTML

 

原因是转换后的Word并不能立即 Quit ,也就是不能马上释放资源

造成另存为后的HTML仍被Word使用

 

比较菜,没什么妙招,所以Thread.Sleep()了一下,等待Word释放资源

 

大概测了一下20ms~50ms比较危险,有时可以,有时候不行

75ms的时候就比较合适,而我还是选了100ms

 

带图片的Word转换会多产生一个文件夹存放图片,HTML的img引用图片的路径不是我想要的

目录结构我更不想改变

 

我的方案是在上传word的时候就直接存在图片目录,然后再在读取的时候改写img的路径,最后存入数据库

(保存在图片路径是因为方面放置图片文件夹)

 

//Tools.IMGREGEX为Regex regex = new Regex("<img[^>]*src[^>]*>");

StringBuilder stringBuilder = new StringBuilder();
FileStream fileStream = new FileStream(savefilename, FileMode.Open);
StreamReader streamReader = new StreamReader(fileStream, Encoding.Default);
string aline;
const string scrAttr = "src=\"";
for (; (aline = streamReader.ReadLine()) != null; ) {
  if (aline.IndexOf("img") != -1) {
    if (Tools.IMGREGEX.IsMatch(aline)) {
      int start = aline.IndexOf(scrAttr) + scrAttr.Length;
      aline = aline.Insert(start, _wordImagePath);
    }
  }
  stringBuilder.Append(aline);
}
streamReader.Close();
fileStream.Close();
return stringBuilder;

 

收工

posted on 2010-11-16 15:36  猥琐代码男  阅读(1343)  评论(1)    收藏  举报