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


        }

 

posted on 2020-12-27 14:50  不知勿言  阅读(2471)  评论(0编辑  收藏  举报