如何將整個行從工作表1複製到下一個可用空行上的同一電子表格的另一個工作表(2)?例如第1行和第2行不是空的,我如何將複製的行從表1粘貼到表2的第3行以及使用Java的後續行?將整個行從Sheet1(源)複製到Sheet2(目標)的下一個可用行
這是我工作的代碼: 我找到了一個代碼,它將行按下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;
}
}
}
}
您可以檢查Sheet2中有多少行,並將其用作下一空閒行的索引。 – IQV
嗨,謝謝Doshi,實際上工作表2是空白的,它只包含頭文件,我在stackoverflow中發現了一個代碼,如果它不是空的,它會將整行向下移動,我需要的是跳過具有值的行並從工作表粘貼複製的行1下面 – Sachi