如何使用Apache POI从现有的Excel表格复制到新的Excel表格?

我想比较两个Excel表,并发现是否有不同的行,如果是这样我想复制一个不同于该Excel的单行到一个新的Excel中的新行。 下面是我从网上拿到的代码片段,但尝试,但如果我复制现有的Excel的第10行(例如)新的Excel的第一行的问题,第一行是正确地复制在新的Excel中,但所有其余的行从第一个excel也复制到新的。 我认为问题是用我写入新的Excel [workbook.write(out)]的方式请帮助! 提前致谢!!

public class RowCopy { public static void main(String[] args) throws Exception{ HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream("c:/input.xls")); HSSFSheet sheet = workbook.getSheet("Sheet1"); copyRow(workbook, sheet, 0, 1); FileOutputStream out = new FileOutputStream("c:/output.xls"); workbook.write(out); out.close(); } private static void copyRow(HSSFWorkbook workbook, HSSFSheet worksheet, int sourceRowNum, int destinationRowNum) { // Get the source / new row HSSFRow newRow = worksheet.getRow(destinationRowNum); HSSFRow sourceRow = worksheet.getRow(sourceRowNum); // If the row exist in destination, push down all rows by 1 else create a new row if (newRow != null) { worksheet.shiftRows(destinationRowNum, worksheet.getLastRowNum(), 1); } else { newRow = worksheet.createRow(destinationRowNum); } // Loop through source columns to add to new row for (int i = 0; i < sourceRow.getLastCellNum(); i++) { // Grab a copy of the old/new cell HSSFCell oldCell = sourceRow.getCell(i); HSSFCell newCell = newRow.createCell(i); // If the old cell is null jump to next cell if (oldCell == null) { newCell = null; continue; } // Copy style from old cell and apply to new cell HSSFCellStyle newCellStyle = workbook.createCellStyle(); newCellStyle.cloneStyleFrom(oldCell.getCellStyle()); ; newCell.setCellStyle(newCellStyle); // If there is a cell comment, copy if (oldCell.getCellComment() != null) { newCell.setCellComment(oldCell.getCellComment()); } // If there is a cell hyperlink, copy if (oldCell.getHyperlink() != null) { newCell.setHyperlink(oldCell.getHyperlink()); } // 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; } } 

}

只需修改copyRow方法,添加参数HSSFSheet resultSheet然后在方法中修改newRowvariables,从resultSheet像这样

 private static void copyRow(HSSFWorkbook workbook, HSSFSheet worksheet, HSSFSheet resultSheet, int sourceRowNum, int destinationRowNum) { // Get the source / new row HSSFRow newRow = resultSheet.getRow(destinationRowNum); HSSFRow sourceRow = worksheet.getRow(sourceRowNum); 

从你的目的地“result.xls”