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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM