如何使用 POI 删除合并区域? [英] How to remove Merged region using POI?

查看:166
本文介绍了如何使用 POI 删除合并区域?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我们可以使用 sheet.addMergedRegion(range) 合并单元格.我想知道如何删除合并.

I know we can merge cells using sheet.addMergedRegion(range). I want to know how to remove merge.

  1. 我们可以使用 sheet.removeMergedRegion(int) 吗
  2. 如果是,那么告诉我应该是什么论点
  3. 合并单元格中的数据会发生什么变化.

推荐答案

快速解答

  1. 是的
  2. sheet中合并区域的id
  3. 数据保存在区域的第一个单元格中,其他单元格为空

说明

您可以使用 sheet.getMergedRegion(i) 获取合并区域,其中 i 是其在工作表中的标识符.

Explanation

You can get the merged regions with sheet.getMergedRegion(i), where i is its identifier in the sheet.

/* ... initialize your workbook and sheet here ... */

// Loop through every merged region in the sheet
for(int i=0; i < sheet.getNumMergedRegions(); ++i)
{
    // Delete the region
    sheet.removeMergedRegion(i);
}

当你做这样的事情时,合并区域的内容将保留在该区域的第一个单元格(左上角)中.其他单元格的内容为空.

When you do such a thing, the content of the merged region will be kept in the first cell of this region (the top-left one). Other cells will have an empty content.

示例:如果您已将(A1 和 A2)与内容合并区域"合并,拆分的结果将为 (A2) 空且 (A1) 内容为合并区域".

Example: If you have (A1 and A2) merged with the content "merged region", the result of the split will be (A2) empty and (A1) with the content "merged region".

请注意,这是内部存储数据的方式,即使您尝试获取包含在合并区域中的单元格的值也是如此.保持相同的示例,您将:

Note that this is how the data is stored internally, even when you try to get the value of a cell contained in a merged region. Keeping the same example, you will have:

CellReference ref = new CellReference("A1");
Row row = sheet.getRow( ref.getRow() );
Cell cell = row.getCell( ref.getCol() );
System.out.println( new DataFormatter().formatCellValue(cell) ); // Will print "merged region"

ref = new CellReference("A2");
row = sheet.getRow( ref.getRow() );
cell = row.getCell( ref.getCol() );
System.out.println( new DataFormatter().formatCellValue(cell) ); // Will print empty string

在移除合并区域之前和之后,这将是相同的行为.

This will be the same behaviour before and after removing the merged region.

如果你想得到一个特定的合并区域来分割它,你必须在你的循环中添加一个条件来识别它:

If you want to get a specific merged region to split it, you will have to add a condition in your loop to identify it:

// If we want to split the merged cell starting at D3
CellReference ref = new CellReference("D3");

for(int i=0; i < sheet.getNumMergedRegions(); ++i)
{
    CellRangeAddress range = sheet.getMergedRegion(i);

    if ( range.getFirstRow() == ref.getRow() && range.getLastRow() == ref.getCol() )
    {
        sheet.removeMergedRegion(i);
    }
}

这篇关于如何使用 POI 删除合并区域?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆