C#读取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}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值