扩展迈克的答案。您可以创建一个ContentHandler
来定位合并区域,例如:
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.ss.util.CellRangeAddress;
import org.xml.sax.Attributes;
import org.xml.sax.helpers.DefaultHandler;
public class MergedRegionLocator extends DefaultHandler {
private final List<CellRangeAddress> mergedRegions = new ArrayList<>();
@Override
public void startElement (String uri, String localName, String name, Attributes attributes) {
if ("mergeCell".equals(name) && attributes.getValue("ref") != null) {
mergedRegions.add(CellRangeAddress.valueOf(attributes.getValue("ref")));
}
}
public CellRangeAddress getMergedRegion (int index) {
return mergedRegions.get(index);
}
public List<CellRangeAddress> getMergedRegions () {
return mergedRegions;
}
}
将其与 POI 基于事件的解析一起使用的示例:
OPCPackage pkg = OPCPackage.open(new FileInputStream("test.xlsx"));
XSSFReader reader = new XSSFReader(pkg);
InputStream sheetData = reader.getSheetsData().next();
MergedRegionLocator mergedRegionLocator = new MergedRegionLocator();
XMLReader parser = XMLReaderFactory.createXMLReader();
parser.setContentHandler(mergedRegionLocator);
parser.parse(new InputSource(sheetData));
mergedRegionLocator.getMergedRegions();