将整行从Sheet1(源)复制到Sheet2(目标)的下一个可用行

时间:2017-04-06 06:57:24

标签: java selenium

如何将整个行从表1复制到下一个可用空行的同一电子表格的另一张表(2)?例如,第1行和第2行不为空,如何使用Java将复制的行从工作表1粘贴到工作表2的第3行和后续行?

以下是我正在处理的代码: 我找到了一个代码,它将行向下推1,但我需要填充下一个可用行的代码。

public class CopyFromExcel {

    public static void copyFromExcel(data) throws Exception {

        String rowNumber = data.gr.getRowNumber();
        int rowNum = Integer.parseInt(rowNumber);

        XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream("file path + filename.xlsx"));
        XSSFSheet sourcesheet = workbook.getSheet("sourcesheetname");
        XSSFSheet resultsheet = workbook.getSheet("destinationsheetname");
        copyRow(workbook, sourcesheet, resultsheet, rowNum, 1);
        FileOutputStream fos = new FileOutputStream(file path + filename.xlsx");
        workbook.write(fos);
        fos.close();
    }

    private static void copyRow(XSSFWorkbook workbook, XSSFSheet sourcesheet, XSSFSheet resultsheet, int sourceRowNum, int destinationRowNum) {
        XSSFRow newRow = resultsheet.getRow(destinationRowNum);
        XSSFRow sourceRow = sourcesheet.getRow(sourceRowNum);

        // If the row exist in destination, push down all rows by 1 else create a new row
        if (newRow != null) {
            resultsheet.shiftRows(destinationRowNum, resultsheet.getLastRowNum(), 1);
        }else{
            newRow = resultsheet.createRow(destinationRowNum);
        }

        // Loop through source columns to add to new row
        for (int i = 0; i < sourceRow.getLastCellNum();  i++) {

            XSSFCell oldCell = sourceRow.getCell(i);
            XSSFCell newCell = newRow.createCell(i);

            // If the old cell is null jump to next cell
            if (oldCell == null){
                newCell = null;
                continue;
            }

            // Set the cell data type
            newCell.setCellType(oldCell.getCellType());

            // Set the cell data value
            switch (oldCell.getCellType()) {
                case Cell.CELL_TYPE_BLANK:
                    newCell.setCellValue(oldCell.getStringCellValue());
                    break;
                case Cell.CELL_TYPE_BOOLEAN:
                    newCell.setCellValue(oldCell.getBooleanCellValue());
                    break;
                case Cell.CELL_TYPE_ERROR:
                    newCell.setCellErrorValue(oldCell.getErrorCellValue());
                    break;
                case Cell.CELL_TYPE_FORMULA:
                    newCell.setCellFormula(oldCell.getCellFormula());
                    break;
                case Cell.CELL_TYPE_NUMERIC:
                    newCell.setCellValue(oldCell.getNumericCellValue());
                    break;
                case Cell.CELL_TYPE_STRING:
                    newCell.setCellValue(oldCell.getRichStringCellValue());
                    break;
            }
        }   

    }
}

1 个答案:

答案 0 :(得分:0)

您可以在工作表上使用getLastRowNum()并使用递增相同来获取空行。