我尝试使用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();
执行成功,使用新值修改了文件,但没有任何内容复制到第一个文件。