C#2.0 读word的多个表格到DataGridView或是其它控件 XP Vista

 1 #region DataTalbe 要考虑第一行是表头,第二行开始为数据
 2 
 3             try
 4             {
 5                 //tablePos表格序号,就是查找word文档几个表格的自动给的序号
 6                 for (int tablePos = 1; tablePos <= oDoc.Tables.Count; tablePos++)
 7                 {
 8 
 9                     string t = tablePos.ToString();
10                     DataSet ds = new DataSet();
11                     DataTable dt = new DataTable(t);
12                     // DataGridView dgv = new DataGridView();
13                     ds.Tables.Add(dt);
14 
15                     Word.Table nowTable = oDoc.Tables.Item(tablePos);
16                     DataRow dr;
17 
18                     //取得第一行标题值
19                     for (int rowPos = 1; rowPos <= nowTable.Rows.Count; rowPos++)
20                     {
21                         //第一行值                               
22                         if (rowPos == 1)
23                         {
24                             for (int columPos = 1; columPos <= nowTable.Columns.Count; columPos++)
25                             {
26                                 string tableMessage = nowTable.Cell(rowPos, columPos).Range.Text;
27                                 tableMessage = tableMessage.Remove(tableMessage.Length - 22).Trim(); ;
28                                 //只求到了第一行值  
29                                 dt.Columns.Add(tableMessage);
30 
31 
32 
33                             }
34                         }
35                         else
36                         {
37                             //第二行值
38                             dr = dt.NewRow();
39                             for (int columPos = 1; columPos <= nowTable.Columns.Count; columPos++)
40                             {
41                                 string tableMessage = nowTable.Cell(rowPos, columPos).Range.Text;
42                                 tableMessage = tableMessage.Remove(tableMessage.Length - 22).Trim();
43                                 dr[columPos - 1= tableMessage;
44 
45                             }
46                             dt.Rows.Add(dr);
47 
48                         }
49                     }
50 
51                     dataGridView1.DataSource = ds.Tables[t].DefaultView;
52                    
53                 }
54 
55 
56             }
57             catch (Exception ex)
58             {
59                 //throw;
60                 MessageBox.Show("你选择的文档不是表格格式不对""提示");
61             }
62             oReadOnly = true;
63             Cursor = Cursors.Default;
64             #endregion
posted @ 2009-03-19 21:50  ®Geovin Du Dream Park™  阅读(577)  评论(0编辑  收藏  举报