关于Excel 相同内容上下单元格合并的方法

转发一下,以备后用。这个对于使用Excel输出报表的人来说很有用。具体功能没验证,以后再说吧。

    /// <summary>
2         /// 合并指定EXCEL的单元格 相同内容的
3         /// </summary>
4         /// <param name="mySheet">指定的EXCEL工作表</param>
5         /// <param name="startLine">起始行</param>
6         /// <param name="recCount">总行数</param>
7         /// <param name="col">要合并的列</param>
8         private void MergeCell_Second(ref Worksheet mySheet, int startLine, int recCount, string col)
9         {
10             string qy1 = mySheet.get_Range(col + startLine.ToString(), col + startLine.ToString()).Text.ToString();//获得起始行合并列单元格的填充内容
11
12             Range rg1;
13             string strtemp = "";
14             bool endCycle = false;
15
16             //从起始行到终止行做循环
17             for (int i = startLine; i <= recCount + startLine - 1&&!endCycle; )
18             {
19                 for (int j = i + 1; j <= recCount + startLine - 1; j++)
20                 {
21                     rg1 = mySheet.get_Range(col + j.ToString(), col + j.ToString());//获得下一行的填充内容
22                     strtemp = rg1.Text.ToString().Trim();
23
24                     if (strtemp.Trim()==qy1.Trim() )//内容等于初始内容
25                     {
26                         rg1 = mySheet.get_Range(col + i.ToString(), col + j.ToString());//选取上条合并位置和当前行的合并区域
27                         rg1.ClearContents();//清空要合并的区域
28                         rg1.MergeCells = true;
29                         if (col == "A")
30                             mySheet.Cells[i, 1] = qy1;
31                         else if (col == "B")
32                             mySheet.Cells[i, 2] = qy1;
33
34                         if (j== recCount + startLine - 1)
35                         {
36                             endCycle = true;
37                         }
38                     }
39                     else//内容不等于初始内容
40                     {
41                         i = j;//i获取新值
42                         qy1 = mySheet.get_Range(col + j.ToString(), col + j.ToString()).Text.ToString();
43                         break;
44                     }
45                 }
46             }
47         }

 

你可能感兴趣的:(工作,String,Excel,报表)