1. 程式人生 > 實用技巧 >NPOI 動態新增行

NPOI 動態新增行

使用excel模板匯出資料時,模板可填充的資料行有限,可通過ShiftRows插入行,如圖,在第七行後插入新行,要求新行包含原有樣式

插入後

首先新增npoi類庫引用

/// <summary>
        /// NPOI使用ShiftRows向excel插入行,並複製原有樣式
        /// </summary>
        /// <param name="file">模板檔案,包含物理路徑</param>
        /// <param name="dir">匯出路徑</param>
        public
void ShiftRows(string file,string dir) { //建立Excel檔案的物件 FileStream fs = new FileStream(file, FileMode.Open); HSSFWorkbook workbook = new HSSFWorkbook(fs); ISheet sheet = (HSSFSheet)workbook.GetSheetAt(0);
int startRow = 7;//開始插入行索引 //excel sheet模板預設可填充4行資料 //當匯出的資料超出4行時,使用ShiftRows插入行 if (list.Count > 4) { //插入行 sheet.ShiftRows(startRow, sheet.LastRowNum, list.Count - 4, true, false); var rowSource = sheet.GetRow(3
); var rowStyle = rowSource.RowStyle;//獲取當前行樣式 for (int i = startRow; i < startRow+list.Count-4; i++) { var rowInsert = sheet.CreateRow(i); if (rowStyle != null) rowInsert.RowStyle = rowStyle; rowInsert.Height = rowSource.Height; for (int col = 0; col < rowSource.LastCellNum; col++) { var cellsource = rowSource.GetCell(col); var cellInsert = rowInsert.CreateCell(col); var cellStyle = cellsource.CellStyle;                //設定單元格樣式     if (cellStyle != null) cellInsert.CellStyle = cellsource.CellStyle; } } } //繫結資料 for (int j = 0; j < list.Count; j++) { //單元格賦值等其他程式碼 IRow r = sheet.GetRow(j + 3); r.Cells[0].SetCellValue(j + 1); } //後續操作。。。。。。。。。。 }