merge 2
using OfficeOpenXml;
using OfficeOpenXml.Style;
using System;
using System.IO;
class Program
{
static void Main()
{
// Required by EPPlus
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
string filePath = @"C:\Temp\input.xlsx"; // Input file
string outputPath = @"C:\Temp\output.xlsx"; // Output file
string sheetName = "Config"; // Target sheet
using (var package = new ExcelPackage(new FileInfo(filePath)))
{
var worksheet = package.Workbook.Worksheets[sheetName];
if (worksheet == null)
{
Console.WriteLine($"Sheet {sheetName} not found!");
return;
}
int startRow = worksheet.Dimension.Start.Row + 1; // skip header row
int endRow = worksheet.Dimension.End.Row;
// Columns B, C, D → Excel is 1-based (B=2, C=3, D=4)
int[] colsToCheck = { 2, 3, 4 };
foreach (int col in colsToCheck)
{
int mergeStart = startRow;
string prevValue = worksheet.Cells[startRow, col].Text;
for (int row = startRow + 1; row <= endRow; row++)
{
string currentValue = worksheet.Cells[row, col].Text;
// If values are different, OR previous value was empty → stop merge
if (currentValue != prevValue || string.IsNullOrWhiteSpace(prevValue))
{
if (row - 1 > mergeStart && !string.IsNullOrWhiteSpace(prevValue))
{
// Merge block
worksheet.Cells[mergeStart, col, row - 1, col].Merge = true;
worksheet.Cells[mergeStart, col, row - 1, col].Style.VerticalAlignment = ExcelVerticalAlignment.Center;
worksheet.Cells[mergeStart, col, row - 1, col].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
}
mergeStart = row;
prevValue = currentValue;
}
}
// Handle last block (if not empty)
if (endRow > mergeStart && !string.IsNullOrWhiteSpace(prevValue))
{
worksheet.Cells[mergeStart, col, endRow, col].Merge = true;
worksheet.Cells[mergeStart, col, endRow, col].Style.VerticalAlignment = ExcelVerticalAlignment.Center;
worksheet.Cells[mergeStart, col, endRow, col].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
}
}
package.SaveAs(new FileInfo(outputPath));
Console.WriteLine("Excel file processed and saved successfully!");
}
}
}
Comments
Post a Comment