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

  • 相关阅读:
    解决Xcode 7编译错误:does not contain bitcode
    iOS无处不在详解iOS集成第三方登录(SSO授权登录无需密码)
    iOS- 如何集成支付宝
    99.Recover Binary Search Tree
    101.Symmetric Tree
    108.Convert Sorted Array to Binary Search Tree
    242.Valid Anagram
    292.Nim Game
    872.Leaf-Similar Trees
    HDU-1390 Binary Numbers
  • 原文地址:https://www.cnblogs.com/scnuwangjie/p/4802360.html
Copyright © 2011-2022 走看看