程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> 關於C語言 >> C#實現在Excel中將連續多列相同數據項合並

C#實現在Excel中將連續多列相同數據項合並

編輯:關於C語言
 效果圖如下:

代碼如下:

/**//// <summary>
        /// 合並工作表中指定行數和列數數據相同的單元格
        /// </summary>
        /// <param name="sheetIndex">工作表索引</param>
        /// <param name="beginRowIndex">開始行索引</param>
        /// <param name="beginColumnIndex">開始列索引</param>
        /// <param name="rowCount">要合並的行數</param>
        /// <param name="columnCount">要合並的列數</param>
        public void MergeWorkSheet(int sheetIndex,int beginRowIndex,int beginColumnIndex,int rowCount,int columnCount)
        {

            //檢查參數
            if ( columnCount < 1 || rowCount < 1)
                return ;

            for(int col=0;col<columnCount;col++)
            {
                int mark = 0;            //標記比較數據中第一條記錄位置
                int mergeCount = 1;        //相同記錄數,即要合並的行數
                string text = "";
               
                for(int row=0;row<rowCount;row++)
                {
                    string prvName = "";
                    string nextName = "";

                    //最後一行不用比較
                    if( row + 1 < rowCount)       
                    {
                        for(int n=0;n<=col;n++)
                        {
                            range = (Excel.Range)workSheet.Cells[row + beginRowIndex,n + beginColumnIndex];
                            range = (Excel.Range)range.MergeArea.get_Item(1,1);
                            text = range.Text.ToString();
                            prvName = prvName + text;

                            range = (Excel.Range)workSheet.Cells[row + 1 + beginRowIndex,n + beginColumnIndex];
                            range = (Excel.Range)range.MergeArea.get_Item(1,1);
                            nextName = nextName + range.Text.ToString();

                        }
                           
                        if(prvName == nextName)
                        {
                            mergeCount++;

                            if(row == rowCount - 2)
                            {
                                this.MergeCells(sheetIndex,beginRowIndex + mark,beginColumnIndex + col,beginRowIndex + mark + mergeCount - 1,beginColumnIndex + col,text);
                            }
                        }
                        else
                        {
                            this.MergeCells(sheetIndex,beginRowIndex + mark,beginColumnIndex + col,beginRowIndex + mark + mergeCount - 1,beginColumnIndex + col,text);
                            mergeCount = 1;
                            mark = row + 1;
                        }
                           
                    }       
                }
            }
        }

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved