1. 程式人生 > >C#使用NPOI向Excel版當中插入行

C#使用NPOI向Excel版當中插入行

#region Excel複製行

        /// <summary>
        /// Excel複製行
        /// </summary>
        /// <param name="wb"></param>
        /// <param name="sheet"></param>
        /// <param name="starRow"></param>
        /// <param name="rows"></param>
        private void insertRow(HSSFWorkbook wb, HSSFSheet sheet, int starRow, int rows)
        {
            /*
             * ShiftRows(int startRow, int endRow, int n, bool copyRowHeight, bool resetOriginalRowHeight);
             *
             * startRow 開始行
             * endRow 結束行
             * n 移動行數
             * copyRowHeight 複製的行是否高度在移
             * resetOriginalRowHeight 是否設定為預設的原始行的高度
             *
             */

            sheet.ShiftRows(starRow + 1, sheet.LastRowNum, rows, true, true);
           
            starRow = starRow - 1;

            for (int i = 0; i < rows; i++)
            {

                HSSFRow sourceRow = null;
                HSSFRow targetRow = null;
                HSSFCell sourceCell = null;
                HSSFCell targetCell = null;

                short m;

                starRow = starRow + 1;
                sourceRow = (HSSFRow)sheet.GetRow(starRow);
                targetRow = (HSSFRow)sheet.CreateRow(starRow + 1);
                targetRow.HeightInPoints = sourceRow.HeightInPoints;

                for (m = (short)sourceRow.FirstCellNum; m < sourceRow.LastCellNum; m++)
                {

                    sourceCell = (HSSFCell)sourceRow.GetCell(m);
                    targetCell = (HSSFCell)targetRow.CreateCell(m);

                    targetCell.Encoding = sourceCell.Encoding;
                    targetCell.CellStyle = sourceCell.CellStyle;
                    targetCell.SetCellType(sourceCell.CellType);

                }
            }

        }

        #endregion