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