zoukankan      html  css  js  c++  java
  • C#读写word

    操作word之前需要在COM引入Microsoft Office 12.0 Object Library(文件库可能不一样)

    然后添加using Microsoft.Office.Interop.Word;

    读操作,docFilename为文件路径 

    private string Doc2Text(string docFileName)        
    { StringBuilder sb
    = new StringBuilder(); ApplicationClass wordApp = new ApplicationClass(); object fileobj = docFileName; object unknow = System.Reflection.Missing.Value; //打开指定文件 try { _Document doc = wordApp.Documents.Open(ref fileobj, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow ); int paragraphsCount = doc.Paragraphs.Count; for (int i = 1; i <= paragraphsCount; i++) { sb.AppendLine(doc.Paragraphs[i].Range.Text.Trim());//获得文档内容 } doc.Close(ref unknow, ref unknow, ref unknow); wordApp.Documents.Save(ref unknow, ref unknow); wordApp.Quit(ref unknow, ref unknow, ref unknow); } catch (Exception) { } return sb.ToString(); }
     

    写操作

     private Boolean WriteLocalFile(string DocFileName, string text)
            {
                try
                {
    
                    object fileobj = DocFileName;
                    object unknow = System.Reflection.Missing.Value;
                    //打开word程序,创建一个新的word文档,但是还没有保存到硬盘中
                    ApplicationClass wordApp = new ApplicationClass();
                    _Document doc = wordApp.Documents.Add(ref unknow, ref unknow, ref unknow, ref unknow);
                    doc.Content.Text += text;
                    //保存word文档
                    doc.SaveAs(ref fileobj, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref  unknow, ref unknow, ref  unknow, ref unknow, ref unknow, ref unknow);
                    doc.Close(ref unknow, ref unknow, ref unknow);
                    wordApp.Documents.Save(ref unknow, ref unknow);
                    wordApp.Quit(ref unknow, ref unknow, ref unknow);
                    return true;
                }
                catch (Exception) { return false; }
            }

    第一次写博客,也是为了记录和分享学过的东西。

    C#操作word内容,可以参考https://msdn.microsoft.com/en-us/library/office/dn320614.aspx

  • 相关阅读:
    代理支持
    CGI
    SSI(服务器端嵌入)
    SSL/TLS 配置
    JSPs
    类加载机制
    JDBC 数据源
    安全管理
    Realm 配置
    Js将序列化成Json格式后日期(毫秒数)转成日期格式
  • 原文地址:https://www.cnblogs.com/scnuwangjie/p/4802360.html
Copyright © 2011-2022 走看看