C# NPOI如何合并Excel中的单元格-完整版

分类:计算机 | C# | C#操作Office | NPOI 320
更新:2020-05-14 22:42:39
编辑
        /// <summary>
        /// 合并excel单元格
        /// </summary>
        /// <param name="filePath">excel文件路径</param>
        /// <param name="startRow">从第几行开始合并</param>
        /// <param name="endRow">到第几行结束合并</param>
        /// <param name="startCol">从第几列开始合并</param>
        /// <param name="endCol">到第几列结束合并</param>
        /// <returns></returns>
        public static bool MergeCell(string filePath, int startRow,int endRow,int startCol,int endCol)
        {
            if (!File.Exists(filePath)) return false;
            FileStream fs = null;
            try
            {
                fs = new FileStream(filePath, FileMode.Open, FileAccess.Read); //打开excel文件流
                IWorkbook workbook = WorkbookFactory.Create(fs); //根据excel文件流创建NPOI的excel工作簿

                ISheet sheet = workbook.GetSheetAt(0); //获取excel第一个sheet
                CellRangeAddress region = new CellRangeAddress(startRow, endRow, startCol, endCol); //设置合并单元格范围
                sheet.AddMergedRegion(region); //合并单元格

                fs.Close();

                //将修改后的excel工作薄先写入内存中,然后保存到本地流
                MemoryStream stream = new MemoryStream();
                workbook.Write(stream);
                var buf = stream.ToArray();
                fs = new FileStream(filePath, FileMode.Create, FileAccess.Write);
                fs.Write(buf, 0, buf.Length);
                fs.Flush();
                fs.Close();
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }