随笔 - 74,  文章 - 1,  评论 - 1,  阅读 - 45048

使用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   不知勿言  阅读(2632)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· 单线程的Redis速度为什么快?
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示