110,533
社区成员
发帖
与我相关
我的任务
分享
//将读取Word表格封装与方法中。
2public string ReadWord(string fileName, int rowIndex, int colIndex)
3{
4 ApplicationClass cls = null;
5 Document doc = null;
6
7 Table table = null;
8 object missing = Missing.Value;
9
10 object path = fileName;
11 cls = new ApplicationClass();
12
13 try
14 {
15 doc = cls.Documents.Open
16 (ref path, ref missing, ref missing, ref missing,
17 ref missing, ref missing, ref missing, ref missing,
18 ref missing, ref missing, ref missing, ref missing,
19 ref missing, ref missing, ref missing, ref missing);
20 table = doc.Tables[1];
21 string text = table.Cell(rowIndex, colIndex).Range.Text.ToString();
22 text = text.Substring(0, text.Length - 2); //去除尾部的mark
23 return text;
24 }
25 catch (Exception ex)
26 {
27
28 return ex.Message;
29 }
30 finally
31 {
32 if (doc != null)
33 doc.Close(ref missing, ref missing, ref missing);
34 cls.Quit(ref missing, ref missing, ref missing);
35 }
36}
这个方法用于读取Word表格中某个单元格的数据。其中的参数分别为文件名(包括路径),行号,列号。
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}