将删除的行插入另一个xls文件

dojqjjoe  于 2021-07-13  发布在  Java
关注(0)|答案(0)|浏览(207)

@axelrichter曾帮助我删除工作簿中的行,但现在我需要在另一个xls文件中插入删除的行。我怎么做这个?

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

import org.apache.poi.ss.usermodel.*;

class RemoveSpecificRows {

 public static void main(String[] args) throws Exception {

  System.out.println("Write material that need to be removed: ");
  java.util.Scanner in = new java.util.Scanner(System.in);
  String toFind = in.nextLine();

  try (Workbook workbook = WorkbookFactory.create(new FileInputStream("ExcelSource.xls")); 
       FileOutputStream fileout = new FileOutputStream("ExcelResult.xls") ) {

   DataFormatter formatter = new DataFormatter();

   Sheet sheet = workbook.getSheetAt(0);

   for (int r = sheet.getLastRowNum(); r >=0;  r--) {
    Row row = sheet.getRow(r);
    if (row != null) {
     for (int c = 0; c < row.getLastCellNum(); c++) {
      Cell cell = row.getCell(c);
      String value = formatter.formatCellValue(cell);
      if (toFind.equals(value)) {
       System.out.println("Text " + toFind + " found at " + cell.getAddress()); 
       //sheet.removeRow(row); //this only empties the row
       sheet.shiftRows(r + 1, sheet.getLastRowNum() + 2, -1); //shift row below up to last row once up
       break;
      }
     }
    }      
   }

   workbook.write(fileout);

  }

 }
}

输出文件是sale.xls,输入是solty.xls

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题