码迷,mamicode.com
首页 > 其他好文 > 详细

NPOI使用ShiftRows向excel插入行,并复制原有样式

时间:2017-11-07 00:13:54      阅读:295      评论:0      收藏:0      [点我收藏+]

标签:logs   img   文件   绑定   .sh   art   lis   mod   stream   

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


        }

 

NPOI使用ShiftRows向excel插入行,并复制原有样式

标签:logs   img   文件   绑定   .sh   art   lis   mod   stream   

原文地址:http://www.cnblogs.com/yanwz/p/7795618.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!