1、C#读取Word文档示例代码在Visual Studio 2005中新建控制台应用程序,命名为GetWordContent添加如下引用:Microsoft.Office.Interop.WordSystem.DrawingSystem.Windows.Forms详细代码如下:using System;using System.Collections.Generic;using System.Text;using System.IO;namespace GetWordContentclass ProgramSTAThreadstatic void Main(string args)/根据Y需要a
2、输?入?正y确的?OA文?档路径?string fileName = “E:ylq_2010GetWordContentGetWordContentbinDebugOA文?档.doc“;bool isOpen = OfficeDocIO.OpenWord(fileName);Console.WriteLine(“打开aWord文?档0是?否?成功|:o1“, Path.GetFileName(fileName), isOpen);Console.WriteLine();Console.WriteLine(“获?取?分?段?落?文?本?内容Y,?段?落?索引y从1开a始?:o“);int par
3、agraph = OfficeDocIO.getParCount();Console.WriteLine(“共2有D0段?“, paragraph);/段?落?索引y从1开a始???for (int i = 1; i / 操作Word的?接口帮?助类/ public class OfficeDocIOprivate static Microsoft.Office.Interop.Word._Application appWord = null;private static Microsoft.Office.Interop.Word._Document docWord = null;/ / 打开
4、a一?个?Word文?档,?相对?的?方?法是?CloseWord()/ / 文?件t名?/ public static bool OpenWord(string file)appWord = new Microsoft.Office.Interop.Word.Application();object path = file;object missing = System.Reflection.Missing.Value;object readOnly = true;trydocWord = appWord.Documents.Open(ref path, ref missing, ref r
5、eadOnly, ref missing,ref missing, ref missing, ref missing, ref missing,ref missing, ref missing, ref missing, ref missing,ref missing, ref missing, ref missing, ref missing);return true;catch (Exception e)Console.WriteLine(e.Message);appWord = null;return false;/ / 读取?word文?档的?第i段?/ / / public stat
6、ic object ReadPar(int i)trystring temp = docWord.Paragraphsi.Range.Text;return temp;catch (Exception e)Console.WriteLine(“Error:“ + e.ToString();return null;/ / 返回?word文?档一?共2几?段?/ / public static int getParCount()return docWord.Paragraphs.Count;/ / 获?取?文?档的?文?本?内容Y/ / public static object GetDocCon
7、tent() return docWord.Content.Text;/ / 提取?word文?档中D表格?的?内容Y/ / 表格?索引y/ 行D号?/ 列D号?/ 内容Y类型 1为a文?本? 2为a图?片?/ 提取?出?来的?内容Ypublic static object GetWordTableContent(int tableid, int rowIndex, int colIndex, int type)if (docWord != null tryswitch (type)case 1:if (docWord.Tablestableid.Rows.Count (rowIndex -
8、1)break;case 2:if (docWord.Tablestableid.Rows.Count (rowIndex - 1) appWord.Selection.Copy();System.Drawing.Image image = System.Windows.Forms.Clipboard.GetImage();content = image;if (image = null)content = ish;break;default:break;return content;catch (Exception e)Console.WriteLine(e.Message);return
9、null;/ / 关?闭?打开a的?word文?档/ public static void CloseWord()object missing = System.Reflection.Missing.Value;tryif (docWord != null)docWord.Close(ref missing, ref missing, ref missing);docWord = null;if (appWord != null)appWord.Quit(ref missing, ref missing, ref missing);appWord = null;catch (Exception e)Console.WriteLine(e.Message); 程序运行结果如图: