方法名:ShiftRows(int startRow, int endRow, int moveNum, bool CopyRowHeight, bool resetRowHeight)
說明:移動行
參數:startRow-待移動行範圍起始索引
endRow-待移動行範圍截止索引
moveNum-要移動的行數
CopyRowHeight-是否複製行高
resetRowHeight-行移動後,源行高是否還原爲excel默認高度
注:此方法存在Bug,當被移動的行中有合併單元格時會報“索引超出範圍”的錯誤
不完美解決辦法:重寫一個移動行方法MoveRows,但是不能有行合併的情況
/// <summary>
/// 移動行
/// </summary>
/// <param name="sheet"></param>
/// <param name="startRow">被移動的起始行號</param>
/// <param name="endRow">被移動的終止行號</param>
/// <param name="moveRowNum">移動行數</param>
/// <param name="copyRowHeight">是否複製行高</param>
/// <param name="resetOriginalRowHeight">源行是否還原爲默認行高</param>
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); } }