SXSSFSheet的shiftRow源码
时间: 2024-05-04 13:18:23 浏览: 77
SXSSFSheet类是Apache POI中SXSSF工作簿的实现,可以用于处理大量数据的Excel文件。shiftRow方法是用来移动行的,下面是该方法的源码:
```java
public void shiftRows(int startRow, int endRow, int n) {
try {
// Do nothing if we don't need to actually shift anything
if(n == 0) {
return;
}
// Handle rows being shifted off the edge of the workbook
if(startRow < 0) {
startRow = 0;
}
if(endRow > lastrow) {
endRow = lastrow;
}
// Handle rows being shifted past the end of the workbook
if(startRow > lastrow) {
int nBlankRows = startRow - lastrow;
for(int i = 0; i < nBlankRows; i++) {
createRow(lastrow + i);
}
}
if(endRow < 0) {
int nBlankRows = -endRow;
for(int i = 0; i < nBlankRows; i++) {
createRow(0);
}
}
// Shift rows
for(int i = startRow; i <= endRow; i++) {
XSSFRow row = getRow(i);
if(row != null) {
row.shift(n);
}
}
// Adjust last row
lastrow += n;
// Remove any rows that have been shifted off the edge of the workbook
Iterator<Row> it = _rows.tailMap(lastrow + 1).values().iterator();
while(it.hasNext()) {
XSSFRow r = (XSSFRow)it.next();
r.removeAllCells();
it.remove();
}
// Update the position of any merged regions that intersect the affected rows
for(CellRangeAddress region : mergedRegions) {
if(region.getFirstRow() >= startRow && region.getLastRow() <= endRow) {
region.setFirstRow(region.getFirstRow() + n);
region.setLastRow(region.getLastRow() + n);
} else if(region.getFirstRow() >= startRow && region.getFirstRow() <= endRow) {
region.setFirstRow(region.getFirstRow() + n);
} else if(region.getLastRow() >= startRow && region.getLastRow() <= endRow) {
region.setLastRow(region.getLastRow() + n);
}
}
} catch(Exception e) {
throw new RuntimeException(e);
}
}
```
该方法接受三个参数:起始行、结束行和移动的行数。如果行数为0,则不进行移动操作。
在移动行之前,该方法会先处理行超出工作簿边缘的情况。若起始行小于0,则将其设为0;若结束行大于最后一行,则将其设为最后一行。若起始行大于最后一行,则需要创建新的空白行;若结束行小于0,则需要在工作簿的最前面创建新的空白行。
然后,该方法会遍历需要移动的行,调用XSSFRow对象的shift方法进行移动。
移动行后,该方法会更新最后一行的位置,并删除移动到工作簿边缘之外的行。最后,该方法会更新与受影响的行交叉的合并区域的位置。
阅读全文