C#合并Excel单元格
本文根据《C#编程典型实例解析》中例题一整理。
合并前EXCEL表格:
合并后EXCEL表格:
整理的函数如下:
代码
1 /// <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 }
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 }
调用方法如下:
1 MergeCell_Second(ref mySheet,3,recordCount,"A");//调用函数实现A列合并
2 MergeCell_Second(ref mySheet, 3, recordCount, "B");//调用函数实现B列合并
2 MergeCell_Second(ref mySheet, 3, recordCount, "B");//调用函数实现B列合并