C#讀取Word文檔內容代碼


首先要添加引用com組件:

然后引用:

using Word = Microsoft.Office.Interop.Word;

獲取內容:

///
/// 讀取 word文檔 返回內容
///

//////
public static string GetWordContent(string path)
{
try
{
Word.Application app = new Microsoft.Office.Interop.Word.Application();
Type wordType = app.GetType();
Word.Document doc = null;
object unknow = Type.Missing;
app.Visible = false;

object file = path;
doc = app.Documents.Open(ref file,
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 count = doc.Paragraphs.Count;
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= count; i++)
{

sb.Append(doc.Paragraphs[i].Range.Text.Trim());
}

doc.Close(ref unknow, ref unknow, ref unknow);
wordType.InvokeMember("Quit", System.Reflection.BindingFlags.InvokeMethod, null, app, null);
doc = null;
app = null;
//垃圾回收
GC.Collect();
GC.WaitForPendingFinalizers();

string temp=sb.ToString();
//if (temp.Length > 200)
// return temp.Substring(0, 200);
//else
return temp;
}
catch
{
return "";
}
}

 


免責聲明!

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



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