如何删除,不清除Sheet中的行? Apache POI [英] How to delete, not clear row in Sheet ? Apache POI
问题描述
我遇到了一个问题。
我不知道如何删除行而不留空字后空行。
I've faced with a problem. I don't know how to delete row without leaving afterwords empty row.
我正在使用Apache-POI 3.9并且使用下一个代码时出错:
I am using Apache-POI 3.9 and I am getting error using next code :
public List<MeterInfo> addToList(String patternt) throws ParseException, IOException {
List<Object> data = new ArrayList<Object>();
int lastRowNum = sheet.getLastRowNum();
Row row;
for(int i = 0; i < lastRowNum; i++){
row = sheet.getRow(i);
if(patternt.equals(getCurrentString(row))){
data.add(getDataFromRow(row));
sheet.removeRow(row);
sheet.shiftRows(row.getRowNum() + 1, row.getRowNum() + 1, -1);
}
}
saveWorkbook(new File("blabla.xlsx"));
return data;
}
UPDATER VERSION:
我找到了解决方案: https://stackoverflow.com/a/3554129/6812826 ,但我得到空指针,因为我减少每个删除行的lastRowNum。
I've found the solution: https://stackoverflow.com/a/3554129/6812826 , but I am getting null pointer because I am decrease lastRowNum by each deleting row.
这是新版本:
public List<Object> addToList(String pattern) throws ParseException, IOException {
List<Object> data= new ArrayList<Object>();
for (int i = 0; i <= sheet.getLastRowNum(); i++) {
Row row = sheet.getRow(i);
if (pattern.equals(getCurrentString(row))) {
data.add(getMeterInfo(row));
deleteRow(row);
}
}
saveWorkbook(new File("blabla.xlsx"));
return data;
}
private void deleteRow(Row row) {
int lastRowNum = sheet.getLastRowNum();
int rowIndex = row.getRowNum();
if(rowIndex >= 0 && rowIndex < lastRowNum){
sheet.shiftRows(rowIndex + 1, lastRowNum, -1);
}
if(rowIndex == lastRowNum){
Row removingRow = sheet.getRow(rowIndex);
if(removingRow != null){
sheet.removeRow(removingRow);
}
}
}
最后更新:
ManishChristian帮助我解决了这个问题!
LAST UPDATE: ManishChristian helped me resolve this problem !
推荐答案
试试这段代码,它应该可行:
Try this code, it should work:
for(int i = 0; i < sheet.getLastRowNum(); i++)
{
row = sheet.getRow(i);
if(patternt.equals(getCurrentString(row)))
{
data.add(getDataFromRow(row));
// sheet.removeRow(row); NO NEED FOR THIS LINE
sheet.shiftRows(row.getRowNum() + 1, sheet.getLastRowNum() + 1, -1);
i--;
}
}
你需要减少 i每次删除一行时,
一个。并使用 getLastRowNum()
再次获取最后一个行号。
You need to decrease i
by one every time you delete one row. And get the last row number again by using getLastRowNum()
.
这篇关于如何删除,不清除Sheet中的行? Apache POI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!