// 判断合并单元格重载
// 调用时要在输出变量前加 out
public bool isMergeCell(ISheet sheet,int rowNum,int colNum,out int rowSpan,out int colSpan)
{
bool result = false;
rowSpan = 0;
colSpan = 0;
if ((rowNum < 1) || (colNum < 1)) return result;
int rowIndex = rowNum - 1;
int colIndex = colNum - 1;
int regionsCount = sheet.NumMergedRegions;
rowSpan = 1;
colSpan = 1;
for (int i = 0; i < regionsCount; i++ )
{
CellRangeAddress range = sheet.GetMergedRegion(i);
sheet.IsMergedRegion(range);
if (range.FirstRow == rowIndex && range.FirstColumn == colIndex)
{
rowSpan = range.LastRow - range.FirstRow + 1;
colSpan = range.LastColumn - range.FirstColumn + 1;
break;
}
}
try
{
result = sheet.GetRow(rowIndex).GetCell(colIndex).IsMergedCell;
}
catch
{
}
return result;
}
其中 rowSpan 和 colSpan 变量调用时要用 out 行跨度变量a out 列跨度变量b 格式返回给变量存储,
int spanR=0,spanC=0;
bool result=isMergeCell(sheet,5,4,out spanR,out spanC);
此时spanR和spanC返回后的结果就是行列跨度,核心原理就是用了range.LastRow和range.LastColumn读区域表格的最后行列位置
如:
你是用setCellValue()方法赋值的吗?
HSSFRow row = sheet.CreateRow(0);
HSSFCell cell = row.CreateCell(0);
cell.SetCellValue("Merge Test");
HSSFCellStyle style = hssfworkbook.CreateCellStyle();
style.Alignment = HSSFCellStyle.ALIGN_CENTER;
HSSFFont font = hssfworkbook.CreateFont();
font.FontHeight = 20*20;
style.SetFont(font);
cell.CellStyle = style;
sheet.AddMergedRegion(new Region(0, 0, 0, 5));
这段代码是把A1:F1这6个单元格合并,赋值为”Merge Test“然后添加合并区域
启用合并后的左上角的原表格的坐标。注意NPOI表格的序列是否是从零起的。
今天天气不错嚯!