利用poi开源jar包操作Excel时删除行内容与直接删除行的区别
一般情况下,删除行时会面临两种情况:删除行内容但保留行位置、整行删除(删除后下方单元格上移)。对应的删除方法分别是:
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);
- }
- }