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);
            }
           //后續操作。。。。。。。。。。


        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM