Excel中有合并单元格时使用ShiftRows方法报“索引超出范围”错误的解决方法

方法名:ShiftRows(int startRow, int endRow, int moveNum, bool CopyRowHeight, bool resetRowHeight)

说明:移动行

参数:startRow-待移动行范围起始索引

          endRow-待移动行范围截止索引

          moveNum-要移动的行数

          CopyRowHeight-是否复制行高

          resetRowHeight-行移动后,源行高是否还原为excel默认高度

注:此方法存在Bug,当被移动的行中有合并单元格时会报“索引超出范围”的错误

不完美解决办法:重写一个移动行方法MoveRows,但是不能有行合并的情况

/// 
/// 移动行
/// 
/// 
/// 被移动的起始行号
/// 被移动的终止行号
/// 移动行数
/// 是否复制行高
/// 源行是否还原为默认行高
private void MoveRows(ISheet sheet, int startRow, int endRow, int moveRowNum, bool copyRowHeight, bool resetOriginalRowHeight)
        {
            if (moveRowNum == 0)
                return;

            int s, inc;
            if (moveRowNum < 0)
            {
                s = startRow;
                inc = 1;
            }
            else
            {
                s = endRow;
                inc = -1;
            }

            for (int rowNum = s; rowNum >= startRow && rowNum <= endRow && rowNum >= 0 && rowNum < 65536; rowNum += inc)
            {
                IRow sourceRow = sheet.GetRow(rowNum);
                IRow targetRow = sheet.GetRow(rowNum + moveRowNum);
                if (sourceRow == null) continue;

                if (targetRow != null) sheet.RemoveRow(targetRow);

                sourceRow.CopyRowTo(rowNum + moveRowNum);
                targetRow = sheet.GetRow(rowNum + moveRowNum);
                if (copyRowHeight)
                    targetRow.Height = sourceRow.Height;    //复制行高

                if (!resetOriginalRowHeight)
                    sourceRow.Height = ((short)0xff);   //还原行高

                RemoveMergedByRow(sourceRow);
                sheet.RemoveRow(sourceRow);
            }

        }
//删除合并单元格
private void RemoveMergedByRow(IRow row)
        {
            foreach (ICell cell in row.Cells)
            {
                Dimension dimen;
                if (!IsMergedCell(cell, out dimen))
                    continue;


                row.Sheet.RemoveMergedRegion(dimen.MergedIndex);
            }
        }





你可能感兴趣的:(NPOI,EXCEL,ShiftRows,移动行)