我尝试将单元格值从工作表复制到另一个文件的工作表Apache POI
。两个XLSM
文件具有相同的列,但顺序不同。我初始化第一个文件如下:
File file = new File(GlobalVariables.XLSM);
FileInputStream inputStream = new FileInputStream(file);
XSSFWorkbook workbook = XSSFWorkbookFactory.createWorkbook(inputStream);
XSSFSheet sheet = workbook.getSheetAt(0);
XSSFRow row = sheet.getRow(recordcount+4);
Cell cell;
之后我在这个文件中设置了一些单元格:
cell = row.getCell(0);
cell.setCellValue(recordcount+1);
cell = row.getCell(2);
originalDir = originalDir.substring(originalDir.indexOf('\\', 2));
cell.setCellValue(originalDir);
第二个文件,我需要从中将值复制到第一个文件:
File prevfile = new File(PrevResXLS);
FileInputStream prevInputStream = new FileInputStream(prevfile);
XSSFWorkbook prevworkbook = XSSFWorkbookFactory.createWorkbook(prevInputStream);
XSSFSheet prevsheet = prevworkbook.getSheetAt(0);
XSSFRow prevrow = prevsheet.getRow(0);
Cell prevCell;
有一个标志,在这种情况下设置为 1,因此满足条件。我正在寻找以前的值,它属于同一个文件,所以需要复制到第一个。
if(GlobalVariables.PrevRES != 0){
File prevfile = new File(PrevResXLS);
FileInputStream prevInputStream = new FileInputStream(prevfile);
XSSFWorkbook prevworkbook = XSSFWorkbookFactory.createWorkbook(prevInputStream);
XSSFSheet prevsheet = prevworkbook.getSheetAt(0);
XSSFRow prevrow = prevsheet.getRow(0);
Cell prevCell;
try {
for (Row r : prevsheet) {
if (r.getRowNum() == 0) continue;
if (r.getCell(1).toString().equals(trans_filename)) {
cell = prevrow.getCell(21);
cell.setCellValue(r.getCell(21 - 13).toString());
cell = prevrow.getCell(22);
cell.setCellValue(r.getCell(22 - 13).toString());
cell = prevrow.getCell(23);
cell.setCellValue(r.getCell(23 - 13).toString());
cell = prevrow.getCell(24);
cell.setCellValue(r.getCell(24 - 13).toString());
cell = prevrow.getCell(25);
cell.setCellValue(r.getCell(25 - 13).toString());
cell = prevrow.getCell(26);
cell.setCellValue(r.getCell(26 - 13).toString());
cell = prevrow.getCell(27);
cell.setCellValue(r.getCell(27 - 13).toString());
cell = prevrow.getCell(28);
cell.setCellValue(r.getCell(28 - 13).toString());
cell = prevrow.getCell(29);
cell.setCellValue(r.getCell(29 - 13).toString());
cell = prevrow.getCell(30);
cell.setCellValue(r.getCell(30 - 13).toString());
cell = prevrow.getCell(31);
cell.setCellValue(r.getCell(31 - 13).toString());
cell = prevrow.getCell(32);
cell.setCellValue(r.getCell(32 - 13).toString());
cell = prevrow.getCell(33);
cell.setCellValue(r.getCell(33 - 13).toString());
}
}
prevInputStream.close();
} catch (NullPointerException e) {
System.out.print("NPE");
}
}
FileOutputStream fileOut=new FileOutputStream(GlobalVariables.XLSM);
workbook.write(fileOut);
fileOut.close();
执行成功,用新值修改文件,但没有将任何内容复制到第一个文件。