一般情况下,删除行时会面临两种情况:删除行内容但保留行位置、整行删除(删除后下方单元格上移)。对应的删除方法分别是:
void removeRow(Row row)//Remove a row from this sheet. All cells contained in the row are removed as well
public void shiftRows(int startRow,int endRow,int n)//Shifts rows between startRow and endRow n number of rows.
示例代码:
以下代码是使用removeRow()方法删除行内容但保留行位置。代码从d:\中的第一个sheet中删除了第一行。需要注意的是,改变是需要在之后才生效的。
import .*;
import .*;
public class testTools{
public static void main(String[] args){
try {
FileInputStream is = new FileInputStream("d://");
HSSFWorkbook workbook = new HSSFWorkbook(is);
HSSFSheet sheet = (0);
HSSFRow row = (0);
(row);
FileOutputStream os = new FileOutputStream("d://");
(os);
();
();
} catch (Exception e) {
();
}
}
}
以下代码是使用shiftRow实现删除整行的效果。同样,也是需要在进行后才会生效。
import .*;
import .*;
public class testTools{
public static void main(String[] args){
try {
FileInputStream is = new FileInputStream("d://");
HSSFWorkbook workbook = new HSSFWorkbook(is);
HSSFSheet sheet = (0);
(1, 4, -1);//删除第一行到第四行,然后使下方单元格上移
FileOutputStream os = new FileOutputStream("d://");
(os);
();
();
} catch (Exception e) {
();
}
}
}
自己写的一个包装好了的删除excel行的方法(利用shiftRows上移来删除行):
/**
* Remove a row by its index
* @param sheet a Excel sheet
* @param rowIndex a 0 based index of removing row
*/
public static void removeRow(HSSFSheet sheet, int rowIndex) {
int lastRowNum=();
if(rowIndex>=0&&rowIndex<lastRowNum)
(rowIndex+1,lastRowNum,-1);//将行号为rowIndex+1一直到行号为lastRowNum的单元格全部上移一行,以便删除rowIndex行
if(rowIndex==lastRowNum){
HSSFRow removingRow=(rowIndex);
if(removingRow!=null)
(removingRow);
}
}