在 Excel 工作表中使用 JAVA 永久删除空行 Apache POI
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17245948/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Permanently Delete Empty Rows Apache POI using JAVA in Excel Sheet
提问by user2496503
I'd like to permanently delete those rows that are empty have no data of any type! I am doing this like:
我想永久删除那些没有任何类型数据的空行!我这样做:
private void shift(File f){
File F=f;
HSSFWorkbook wb = null;
HSSFSheet sheet=null;
try{
FileInputStream is=new FileInputStream(F);
wb= new HSSFWorkbook(is);
sheet = wb.getSheetAt(0);
int rowIndex = 0;
int lastRowNum = sheet.getLastRowNum();
if (rowIndex >= 0 && rowIndex < lastRowNum) {
sheet.shiftRows(rowIndex, lastRowNum, 500);
}
FileOutputStream fileOut = new FileOutputStream("C:/juni.xls");
wb.write(fileOut);
fileOut.close();
}
catch(Exception e){
System.out.print("SERRO "+e);
}
}
after shiftRows() i write my new file. But my code has now effect. I just need to remove/delete the empty rows that come inside my data (any ever). so is it possible doing so? if yes, am i doing right? if no can anybody please help me doing so? Thanks in advance!
在 shiftRows() 之后我写了我的新文件。但是我的代码现在生效了。我只需要删除/删除数据中的空行(任何时候)。那么有可能这样做吗?如果是,我做得对吗?如果没有,请帮助我这样做吗?提前致谢!
回答by Erik Nguyen
If memory recalls shiftRows(int startRow, int endRow, int n)
is what you need. I don't quite remember how to check if a row is empty but if you DO know that a row is empty (normally through use of removeRow(Row row)
) and you know the rowIndex, then it isn't so bad. By calling:
如果记忆回忆shiftRows(int startRow, int endRow, int n)
是你所需要的。我不太记得如何检查一行是否为空,但是如果您确实知道一行为空(通常通过使用removeRow(Row row)
)并且您知道 rowIndex,那么它并没有那么糟糕。通过调用:
int rowIndex; //Assume already known and this is the row you want to get rid of
int lastIndex = sheet.getLastRowNum();
sheet.shiftRows(rowIndex + 1, lastIndex, -1);
you shift every row in [rowIndex + 1, lastIndex] inclusive up by 1 (which should delete an empty row effectively). If you have multiple rows and had a way to determine if the row was empty then I suggest something like:
您将 [rowIndex + 1, lastIndex] 中的每一行向上移动 1(这应该有效地删除一个空行)。如果您有多行并且有办法确定该行是否为空,那么我建议如下:
for(int i = 0; i < sheet.getLastRowNum(); i++){
if(isEmpty(sheet.getRow(i)){
sheet.shiftRows(i + 1, sheet.getLastRowNum(), -1);
i--;//Adjusts the sweep in accordance to a row removal
}
}
boolean isEmpty(Row row){
//Code to determine if a row is empty
}
As a small note if n
is negative, the rows shift up. If n
is positive the rows shift down. So I'm not quite sure if you meant to shift that chunk of rows down by 500 or not in your provided code. I hope this helps.
作为一个小说明,如果n
为负,则行向上移动。如果n
为正,则行向下移动。所以我不太确定你是否打算在你提供的代码中将那块行向下移动 500。我希望这有帮助。