简体   繁体   中英

Delete a specific row from the xlsx using java

i am trying to compare the filenames with the xlsx sheet ...if the filename matches with the value of the excel sheet...i want to delete that particular row from the excel sheet.... below is the code what i have tried so far ...

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.sl.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class try2 {
    public static void main(String[] args)
            throws FileNotFoundException, IOException {
        File[] files=  new File
                ("C:\\wamp\\www\\ptry\\sample\\xl").listFiles();
        String s = null;
        for(File file:files){
            s=file.getName();
            s=s.replaceAll(".xlsx", "");
            }
            File xl=new File("C:\\wamp\\www\\ptry\\sample\\xl.xlsx");
            FileInputStream f=new FileInputStream(xl);
            XSSFWorkbook wb = new XSSFWorkbook (f);
            XSSFSheet sheet = wb.getSheetAt(0);
            int row=sheet.getLastRowNum()+1;
            int colm=sheet.getRow(0).getLastCellNum();
            for(int i=0;i<row;i++){
                XSSFRow r=sheet.getRow(i);
                String m=cellToString(r.getCell(0));
                if(s.equals(m)){
                    System.out.println(m);
                }
            }
        }


    public static String cellToString(XSSFCell cell) {
        int type;
        Object result = null;
        type = cell.getCellType();
        switch (type) {
            case XSSFCell.CELL_TYPE_STRING:
                result = cell.getStringCellValue();
                break;
            case XSSFCell.CELL_TYPE_BLANK:
                result = "";
                break;
            case XSSFCell.CELL_TYPE_FORMULA:
                result = cell.getCellFormula();
        }
        return result.toString();
    }
    }

here 's' is the variable to hold filenames and 'm' is the variable to hold excel values The PROBLEM is: if i use

   if(s.equals(m))
  {
    System.out.println(m);
  }

HOW TO DELETE THE MATCHED ROW FROM THE EXCEL??? Eg)

File names:

a.xlsx

b.xlsx

c.xlsx

excel.xlsx

a

b

d

c

i want to remove a and b from the excel.xlsx

UPDATED: Based on YASH suggustion i tried the below code

                 if(s.equals(m)){
                    System.out.println(m);
                    sheet.removeRow(r);
                }

it removed the first value from excel.xlsx(a)....and shows Exception in thread "main" java.lang.NullPointerException error in the below line

                     String m=cellToString(r.getCell(0));

i tried with

              XSSFRow r = sheet.getRow(i);
                    if(r==null){
                        continue;
                    }

it takes only two values(a,b) from excel.xlsx

After removing the row with RemoveRow(r) shift the remaining rows by 1 as shown below to avoid NullPointer Exception

    sheet.RemoveRow(r);   

            int rowIndex = r.RowNum;

            int lastRowNum = sheet.LastRowNum;

            if (rowIndex >= 0 && rowIndex < lastRowNum)
        {
            sheet.ShiftRows(rowIndex + 1, lastRowNum, -1);
        }

finally i got the answer

        import java.io.File;
        import java.io.FileInputStream;
        import java.io.FileNotFoundException;
        import java.io.FileOutputStream;
        import java.io.IOException;
        import java.util.ArrayList;
        import java.util.Iterator;
        import java.util.List;
        import java.util.logging.Level;
        import java.util.logging.Logger;
        import javax.swing.JButton;
        import org.apache.poi.EncryptedDocumentException;
        import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
        import org.apache.poi.openxml4j.util.ZipSecureFile;
        import org.apache.poi.sl.usermodel.Sheet;
        import org.apache.poi.ss.usermodel.Cell;
        import org.apache.poi.ss.usermodel.Row;
        import org.apache.poi.ss.usermodel.Workbook;
        import org.apache.poi.ss.usermodel.WorkbookFactory;
        import org.apache.poi.xssf.usermodel.XSSFCell;
        import org.apache.poi.xssf.usermodel.XSSFRow;
        import org.apache.poi.xssf.usermodel.XSSFSheet;
        import org.apache.poi.xssf.usermodel.XSSFWorkbook;

        public class try1 {
           public static void main(String[] args)
        throws FileNotFoundException, IOException {
             File[] files=new File("D:\\aa\\a").listFiles();
                   String s = null;
                                   for(File file:files){
                                    s=file.getName();
                                            s=s.replaceAll(".xlsx", "");  

                    File xl=new File("D:\\aa\\w1.xlsx");
                    FileInputStream f=new FileInputStream(xl);

                   XSSFWorkbook wb = new XSSFWorkbook (f);
                    XSSFSheet sheet = wb.getSheetAt(0);
                    int row=sheet.getLastRowNum();
                int colm=sheet.getRow(0).getLastCellNum();
                for(int i=0;i<row;i++){

                    XSSFRow r = sheet.getRow(i);
                    if(r==null){
                       sheet.getRow(i+1);
                        continue;
                    }
                Cell cell=r.getCell(0);
                String m=cellToString(r.getCell(0));
                if(s.equals(m)){
                  System.out.println("s :"+m);
                   sheet.removeRow(r);

                   }}


                FileOutputStream out= 
            new FileOutputStream(new File("D:\\aa\\w1.xlsx"));
               wb.write(out);
                }               
                     }public static String cellToString(XSSFCell cell) {

                int type;
                Object result = null;
                type = cell.getCellType();
               switch (type) {
                 case XSSFCell.CELL_TYPE_STRING:
                    result = cell.getStringCellValue();
                    break;
                case XSSFCell.CELL_TYPE_BLANK:
                    result = "";
                    break;
                case XSSFCell.CELL_TYPE_FORMULA:
                    result = cell.getCellFormula();
                }

                return result.toString();
            }

        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM