
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using NPOI.HSSF.UserModel; 6 using NPOI.SS.UserModel; 7 using NPOI.SS.Util; 8 9 namespace Helper 10 { 11 public class NPOIHelper 12 { 13 /// <summary> 14 /// 復制行格式並插入指定行數 15 /// </summary> 16 /// <param name="sheet">當前sheet</param> 17 /// <param name="startRowIndex">起始行位置</param> 18 /// <param name="sourceRowIndex">模板行位置</param> 19 /// <param name="insertCount">插入行數</param> 20 public static void CopyRow(ISheet sheet, int startRowIndex, int sourceRowIndex, int insertCount) 21 { 22 IRow sourceRow = sheet.GetRow(sourceRowIndex); 23 int sourceCellCount = sourceRow.Cells.Count; 24 25 //1. 批量移動行,清空插入區域 26 sheet.ShiftRows(startRowIndex, //開始行 27 sheet.LastRowNum, //結束行 28 insertCount, //插入行總數 29 true, //是否復制行高 30 false //是否重置行高 31 ); 32 33 int startMergeCell = -1; //記錄每行的合並單元格起始位置 34 for (int i = startRowIndex; i < startRowIndex + insertCount; i++) 35 { 36 IRow targetRow = null; 37 ICell sourceCell = null; 38 ICell targetCell = null; 39 40 targetRow = sheet.CreateRow(i); 41 targetRow.Height = sourceRow.Height;//復制行高 42 43 for (int m = sourceRow.FirstCellNum; m < sourceRow.LastCellNum; m++) 44 { 45 sourceCell = sourceRow.GetCell(m); 46 if (sourceCell == null) 47 continue; 48 targetCell = targetRow.CreateCell(m); 49 targetCell.CellStyle = sourceCell.CellStyle;//賦值單元格格式 50 targetCell.SetCellType(sourceCell.CellType); 51 52 //以下為復制模板行的單元格合並格式 53 if (sourceCell.IsMergedCell) 54 { 55 if (startMergeCell <= 0) 56 startMergeCell = m; 57 else if (startMergeCell > 0 && sourceCellCount == m + 1) 58 { 59 sheet.AddMergedRegion(new CellRangeAddress(i, i, startMergeCell, m)); 60 startMergeCell = -1; 61 } 62 } 63 else 64 { 65 if (startMergeCell >= 0) 66 { 67 sheet.AddMergedRegion(new CellRangeAddress(i, i, startMergeCell, m - 1)); 68 startMergeCell = -1; 69 } 70 } 71 } 72 } 73 } 74 } 75 }
參考http://www.cnblogs.com/kingangWang/archive/2011/08/31/2161319.html