一般情況下,刪除行時會面臨兩種情況:刪除行內容但保留行位置、整行刪除(刪除后下方單元格上移)。對應的刪除方法分別是:
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. If you use a negative number, it will shift rows up. Code ensures that rows don't wrap around.
示例代碼:
以下代碼是使用removeRow()方法刪除行內容但保留行位置。代碼從d:\test.xls中的第一個sheet中刪除了第一行。需要注意的是,改變是需要在workbook.write之后才生效的。
- import org.apache.poi.hssf.usermodel.*;
- import java.io.*;
- public class testTools{
- public static void main(String[] args){
- try {
- FileInputStream is = new FileInputStream("d://test.xls");
- HSSFWorkbook workbook = new HSSFWorkbook(is);
- HSSFSheet sheet = workbook.getSheetAt(0);
- HSSFRow row = sheet.getRow(0);
- sheet.removeRow(row);
- FileOutputStream os = new FileOutputStream("d://test.xls");
- workbook.write(os);
- is.close();
- os.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
以下代碼是使用shiftRow實現刪除整行的效果。同樣,也是需要在進行workbook.write后才會生效。
- import org.apache.poi.hssf.usermodel.*;
- import java.io.*;
- public class testTools{
- public static void main(String[] args){
- try {
- FileInputStream is = new FileInputStream("d://test.xls");
- HSSFWorkbook workbook = new HSSFWorkbook(is);
- HSSFSheet sheet = workbook.getSheetAt(0);
- sheet.shiftRows(1, 4, -1);//刪除第一行到第四行,然后使下方單元格上移
- FileOutputStream os = new FileOutputStream("d://test.xls");
- workbook.write(os);
- is.close();
- os.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
自己寫的一個包裝好了的刪除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=sheet.getLastRowNum();
- if(rowIndex>=0&&rowIndex<lastRowNum)
- sheet.shiftRows(rowIndex+1,lastRowNum,-1);//將行號為rowIndex+1一直到行號為lastRowNum的單元格全部上移一行,以便刪除rowIndex行
- if(rowIndex==lastRowNum){
- HSSFRow removingRow=sheet.getRow(rowIndex);
- if(removingRow!=null)
- sheet.removeRow(removingRow);
- }
- }