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

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

直接上代码方法

/// 
        /// 向已存在的excel追加数据
        /// 
        /// 已存在的excel路径
        /// 追加行索引
        /// 追加列索引<列索引,单元格值>
        public void addExcelData(string excelPath, int rowIndex, IDictionary 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 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();
        }

你可能感兴趣的:(NPOI)