npoi向已存在的Excel追加数据,保留原有数据

版权声明:转载请注明 https://blog.csdn.net/qq_34720818/article/details/88085667

npoi向已存在的Excel追加数据,保留原有数据

直接上代码方法

/// <summary>
        /// 向已存在的excel追加数据
        /// </summary>
        /// <param name="excelPath">已存在的excel路径</param>
        /// <param name="rowIndex">追加行索引</param>
        /// <param name="cellData">追加列索引<列索引,单元格值></param>
        public void addExcelData(string excelPath, int rowIndex, IDictionary<int, string> cellData)
        {
            FileStream fs = new FileStream(excelPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);//读取流
            POIFSFileSystem ps = new POIFSFileSystem(fs);//需using NPOI.POIFS.FileSystem;
            HSSFWorkbook workbook = new HSSFWorkbook(ps);
            ISheet sheet = workbook.GetSheetAt(0);//获取工作表

            //设置列宽
            SetColumnWidth(sheet, 0, 20);
            SetColumnWidth(sheet, 1, 10);
            IRow row = sheet.GetRow(rowIndex); //得到表头
            //设置行高
            row.Height =2 * 256;

            ICell cell = null;
            ICellStyle style = null;
            foreach (KeyValuePair<int, string> keyValue in cellData)
            {
                if (keyValue.Key == 1)
                {
                    cell = row.CreateCell(keyValue.Key);
                    cell.SetCellValue(keyValue.Value);
                   
                    style = workbook.CreateCellStyle();
                    //设置左对齐
                    style.Alignment = NPOI.SS.UserModel.HorizontalAlignment.LEFT;
                    //设置斜线
                    style.BorderDiagonal = BorderDiagonal.BACKWARD;
                    style.BorderDiagonalLineStyle = NPOI.SS.UserModel.BorderStyle.THIN;
                    //设置换行(若要单元格内换行必须加下面一句)
                    style.WrapText = true;
                    cell.CellStyle = style;
                }
                else
                {
                    cell = row.CreateCell(keyValue.Key);
                    cell.SetCellValue(keyValue.Value);

                    //设置居中
                    style = workbook.CreateCellStyle();
                    style.VerticalAlignment = VerticalAlignment.CENTER;
                    style.Alignment = NPOI.SS.UserModel.HorizontalAlignment.CENTER;
                    cell.CellStyle = style;
                }
            }

            FileStream fout = new FileStream(excelPath, FileMode.Open, FileAccess.Write, FileShare.ReadWrite);//写入流
            fout.Flush();
            workbook.Write(fout);//写入文件
            workbook = null;
            fout.Close();
        }

猜你喜欢

转载自blog.csdn.net/qq_34720818/article/details/88085667