zoukankan      html  css  js  c++  java
  • 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);
                }
               //后续操作。。。。。。。。。。
    
    
            }
  • 相关阅读:
    Ajax跨域解决实例
    关于tween.js测试介绍
    signal() 和 sigaction()
    信号概述
    监控文件事件
    栈和栈帧
    进程结构和内存布局
    关于文件I/o的原子操作
    查询Linux系统中glibc的版本
    IOPS和Throughput
  • 原文地址:https://www.cnblogs.com/yiyanwei/p/14197296.html
Copyright © 2011-2022 走看看