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

  • 相关阅读:
    hdu 5387 Clock (模拟)
    CodeForces 300B Coach (并查集)
    hdu 3342 Legal or Not(拓扑排序)
    hdu 3853 LOOPS(概率DP)
    hdu 3076 ssworld VS DDD(概率dp)
    csu 1120 病毒(LICS 最长公共上升子序列)
    csu 1110 RMQ with Shifts (线段树单点更新)
    poj 1458 Common Subsequence(最大公共子序列)
    poj 2456 Aggressive cows (二分)
    HDU 1869 六度分离(floyd)
  • 原文地址:https://www.cnblogs.com/scnuwangjie/p/4802360.html
Copyright © 2011-2022 走看看