您的位置:首页 > 编程语言 > C#

c# 操作Word总结

2016-03-17 15:31 483 查看

c# 操作Word总结

  在医疗管理系统中为保存患者的体检和治疗记录,方便以后的医生或其他人查看。当把数据保存到数据库中,需要新建很多的字段,而且操作很繁琐,于是想到网页的信息创建到一个word文本中,在显示的时,可以在线打开word,也可以把word转换成html标签显示。 这样使用word代替网页的原因有:   第一:网页生成数学公式和特殊符号存储和显示比较麻烦(如何操作word生成数学公式,有待测试)   第二:生成Word版的报告更容易存档和没有环境下的传阅及打印   第三:客户直接操作Word感觉更亲切,而且非常熟悉   Msdn上的word操作api(不过只有英文版,英文差的先闪过) Word2007的API:http://msdn.microsoft.com/en-us/library/bb257531(v=office.12).aspx Word2010的API:http://msdn.microsoft.com/en-us/library/microsoft.office.interop.word(v=office.14).aspx
  Word对象模型 (.Net Perspective)   五大对象 Application :代表Microsoft Word应用程序本身   是Document和Selection的基类。通过Application的属性和方法,我们可以控制Word的大环境。 Document :代表一个Word文档   当你新建一个Word文档或者打开一个已有的Word文档,你将创建一个Document对象,该对象被加入到Words Documents Collection中。拥有焦点的Document称为ActiveDocument,可以通过Application对象的ActiveDocument属性获得当前文档对象 Selection :代表当前选中的区域(高亮),没有选中区域时代表光标点   它通常是高亮显示的(例如,你要改变一段文字的字体,你首先得选中这段文字,那么选中的这块区域就是当前文档的Selection对象所包含的区域) Bookmarks :书签   1>书签一般有名字   2>Saved with the document,且文档关闭了之后书签继续存在   3>书签通常是隐藏的,但也可以通过代码设置其为可见
Range :代表一块区域,与Selection类似,不过一般不可见   1>包含一个起始位置和一个结束位置   2>它可以包含光标点,一段文本或者整个文档   3>它包含空格,tab以及paragraph marks   4>它可以是当前选中的区域,当然也可以不是当前选中区域   5>它被动态创建   6>当你在一个Range的末尾插入文本,这将扩展该Range

  word文档对象的结构图

public void WordToHtml(string wordFileName)
{
//在此处放置用户代码以初始化页面
Microsoft.Office.Interop.Word.ApplicationClass word = new Microsoft.Office.Interop.Word.ApplicationClass();
Type wordType = word.GetType();
Documents docs = word.Documents;

//打开文件
Type docsType = docs.GetType();
Document doc = (Document)docsType.InvokeMember("Open",
System.Reflection.BindingFlags.InvokeMethod, null, docs, new Object[] { wordFileName, true, true });

//转换格式,另存为
Type docType = doc.GetType();

string wordSaveFileName = wordFileName.ToString();
//配置保存htm文件的地址
string strPath = Server.MapPath("~/Model/Word/Files/");
string strSaveFileName = strPath + "a.html"; //wordSaveFileName.Substring(0, wordSaveFileName.Length - 3) + "html";
object saveFileName = (object)strSaveFileName;

docType.InvokeMember("SaveAs", System.Reflection.BindingFlags.InvokeMethod,
null, doc, new object[] { saveFileName, WdSaveFormat.wdFormatFilteredHTML });

docType.InvokeMember("Close", System.Reflection.BindingFlags.InvokeMethod,
null, doc, null);
//退出 Word
wordType.InvokeMember("Quit", System.Reflection.BindingFlags.InvokeMethod,
null, word, null);

Response.Write("<script language='javascript'>window.open ('Files/a.html', 'newwindow', 'height=600, width=400, top=0, left=0, toolbar=no, menubar=no, scrollbars=no, resizable=no,location=no, status=no')</script>");

}


Word转换Html
转换思路:

  >取得Word文档的本地路径

  >将Word文档转换为html文件

  >将html保存到项目中

  >在当前项目中打开此html文件

局限:

  目前只在IE10测试中可以很好使用,在firefox和chrome测试用均有中文乱码的问题,有待解决。

引用:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: