class WordTableRead
2{
3 private string fileName;
4 private ApplicationClass cls = null;
5 private Document doc = null;
6 private Table table = null;
7 private object missing = Missing.Value;
8 //Word是否处于打开状态
9 private bool openState;
10
11
12 /// <summary>
13 /// 自定义构造方法
14 /// </summary>
15 /// <param name="fileName">包含路径的文件名</param>
16 public WordTableRead(string fileName)
17 {
18 this.fileName = fileName;
19 }
20
21 /// <summary>
22 /// 打开Word文档
23 /// </summary>
24 public void Open()
25 {
26 object path = fileName;
27 cls = new ApplicationClass();
28 try
29 {
30 doc = cls.Documents.Open
31 (ref path, ref missing, ref missing, ref missing,
32 ref missing, ref missing, ref missing, ref missing,
33 ref missing, ref missing, ref missing, ref missing,
34 ref missing, ref missing, ref missing, ref missing);
35 openState = true;
36 }
37 catch
38 {
39 openState = false;
40 }
41 }
42
43 /// <summary>
44 /// 返回指定单元格中的数据
45 /// </summary>
46 /// <param name="tableIndex">表格号</param>
47 /// <param name="rowIndex">行号</param>
48 /// <param name="colIndex">列号</param>
49 /// <returns>单元格中的数据</returns>
50 public string ReadWord(int tableIndex, int rowIndex, int colIndex)
51 {
52 //Give the value to the tow Int32 params.
53
54 try
55 {
56 if (openState == true)
57 {
58 table = doc.Tables[tableIndex];
59 string text = table.Cell(rowIndex, colIndex).Range.Text.ToString();
60 text = text.Substring(0, text.Length - 2); //去除尾部的mark
61 return text;
62 }
63 else
64 {
65 return "";
66 }
67 }
68 catch
69 {
70 return "Error";
71 }
72 }
73
74 /// <summary>
75 /// 关闭Word文档
76 /// </summary>
77 public void Close()
78 {
79 if (openState == true)
80 {
81 if (doc != null)
82 doc.Close(ref missing, ref missing, ref missing);
83 cls.Quit(ref missing, ref missing, ref missing);
84 }
85 }
86}