输入Excel文件.....

25010082512 25002207512 1044 1044 NGN NGN

36620841728 36617009228 1066 1066 NGN NGN

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class RemoveEmptyCellInExcel {

    //shifting empty columns
    public static void shift(File f){
        File F=f;
        HSSFWorkbook workbook = null;
        HSSFSheet sheet=null;
        Boolean isRowEmpty=false;
        try{
            FileInputStream is=new FileInputStream(F);

             workbook= new HSSFWorkbook(is);
             sheet = workbook.getSheetAt(0);
             //sheet.setDisplayGridlines(false);

              for(int i = 3; i < sheet.getLastRowNum(); i++){
                  if(sheet.getRow(i)==null){
                      sheet.shiftRows(i + 1, sheet.getLastRowNum(), -1);
                      i--;
                      continue;
                      }
              for(int j=0; j<sheet.getRow(i).getLastCellNum();j++){

              if(sheet.getRow(i).getCell(j).toString().trim().equals(""))
                {
                   isRowEmpty=true;
              }else {
              isRowEmpty=false;
              break;
              }
          }
          if(isRowEmpty==true){
              sheet.shiftRows(i+ 1, sheet.getLastRowNum(), -1);
              i--;
              }
          }

          //Writing output to the same file.
         FileOutputStream fileOut = new FileOutputStream("--------");
         workbook.write(fileOut);
         fileOut.close();
         System.out.println("Successfully wrote the content in the file");
    }
    catch(Exception e){
        e.printStackTrace();
    }
}


public static void main(String args[]) {
    //Input file path
        File f=new File("------------");
        RemoveEmptyCellInExcel.shift(f);
}


}

我需要以下输出.....


25010082512 25002207512 1044 1044 NGN NGN
36620841728 36617009228 1066 1066 NGN NGN

最佳答案

您的代码过于复杂,尝试使用apach csv来简化:

public static void shift(File file){
final FileReader fr = new FileReader(file.getPath());
final File out = new File(path);
try(CSVPrinter printer = new CSVPrinter(out, CSVFormat.DEFAULT
  .withDelimiter(' ')) {
     final Iterable<CSVRecord> records =
     CSVFormat.DEFAULT.withDelimiter(' ').parse(fr);
     for (final CSVRecord record : records) {
        printer.printRecord(record.get(0),record.get(1), ...,
        record.get(record.size()-1));
     }

关于java - 如何使用Java删除或删除Excel工作表中的空行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56971039/

10-11 02:26