This article is based on the example in C # programming typical instance analysis.
Excel worksheet before merge:
After merging the Excel Worksheet:
The sorting functions are as follows:
Code
1 /// <Summary>
2 /// Merge cells in a specified Excel File
3 /// </Summary>
4 /// <Param name = "mysheet"> Specified Excel worksheet </Param>
5 /// <Param name = "Startline"> Start line </Param>
6 /// <Param name = "reccount"> Total number of rows </Param>
7 /// <Param name = "col"> Columns to be merged </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 (); // Obtains the filling content of cells in the merged column of the starting row.
11
12 Range rg1;
13 String Strtemp = "" ;
14 Bool Endcycle = False ;
15
16 // Loop from starting row to ending row
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 ()); // Get the filling content of the next row
22 Strtemp = Rg1.text. tostring (). Trim ();
23
24 If (Strtemp. Trim () = Qy1.trim ()) // Content Equals initial content
25 {
26 Rg1. = Mysheet. get_range (COL + I. tostring (), Col + J. tostring ()); // Select the merge location of the last row and the merge region of the current row.
27 Rg1.clearcontents (); // Clear the region to be merged
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 // Content is not equal to initial content
40 {
41 I = J; // I get new value
42 Qy1 = Mysheet. get_range (COL + J. tostring (), Col + J. tostring (). Text. tostring ();
43 Break ;
44 }
45 }
46 }
47 }
The call method is as follows:
1 Mergecell_second ( Ref Mysheet, 3 , Recordcount, " A " ); // Call the function to merge column
2 Mergecell_second ( Ref Mysheet, 3 , Recordcount, " B " ); // Use a function to merge columns B