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

  • 相关阅读:
    git push&pull命令详解
    Git常用命令总结
    SpringBoot入门之事件监听
    SpringBoot整合Redis
    十九:JDBC操作事务
    十八:使用JDBC进行批处理
    十七:使用JDBC处理MySQL大数据
    十六:使用JDBC对数据库进行CRUD
    十五:JDBC学习入门
    SpringBoot使用@Scheduled创建定时任务
  • 原文地址:https://www.cnblogs.com/scnuwangjie/p/4802360.html
Copyright © 2011-2022 走看看