为什么在复制 excel 内容期间只设置最后一个值



我正在尝试将Excel文件的内容复制到另一个文件。但只有第一行。

所以,我写了这段代码:

// Step 1 : Locate path and file of input excel
File inputFile = new File("path.xlsx")
FileInputStream fis = new FileInputStream(inputFile)
XSSFWorkbook inputWorkbook = new XSSFWorkbook(fis)
int inputSheetCount = inputWorkbook.getNumberOfSheets()
// Step 2 : Locate path and file of output excel
File outputFile = new File("path2.xlsx")
FileOutputStream fos = new FileOutputStream(outputFile)
// Step 3 : Creating workbook for output excel file
XSSFWorkbook outputWorkbook = new XSSFWorkbook()
// Step 4 : Creating sheets with the same name as appearing in input file
for(int i = 0; i < inputSheetCount; i++) {
    XSSFSheet inputSheet = inputWorkbook.getSheetAt(i)
    String inputSheetName = inputWorkbook.getSheetName(i)
    XSSFSheet outputSheet = outputWorkbook.createSheet(inputSheetName)
    int numberOfColumns = inputSheet.getRow(0).getPhysicalNumberOfCells()
    int columnIndex = 0
    while (columnIndex < numberOfColumns && inputSheet.getRow(0).getCell(columnIndex).stringCellValue != '') {
        // Step 5 : Creating new Row, Cell and Input value in the newly created sheet
        outputSheet.createRow(0).createCell(columnIndex).setCellValue(inputSheet.getRow(0).getCell(columnIndex).stringCellValue)
        columnIndex++
    }
}
// Step 6 : Write all the sheets in the new Workbook using FileOutStream Object
outputWorkbook.write(fos)
// Step 7 : At the end of the Program close the FileOutputStream object
fos.close()

然而,我遇到了一个奇怪的问题。当我检查输出文件时,只设置了最后一个值,没有设置其他值......

输入文件

     A  |  B   |    C
1 | Key  Value   Comment 
2 | 
3 |

输出文件预期结果

     A  |  B   |    C
1 | Key  Value   Comment 
2 | 
3 |

输出文件实际结果

     A  |  B   |    C
1 |              Comment 
2 | 
3 |

有人知道吗?多谢!

while进入

循环。我建议再放一个这样的for

    for(int j=0;j<numberOfColumns ;j++){
    if(inputSheet.getRow(0).getCell(j).stringCellValue != ''){
            // Step 5 : Creating new Row, Cell and Input value in the newly created sheet
            outputSheet.createRow(0).createCell(j).setCellValue(inputSheet.getRow(0).getCell(j).stringCellValue)
        }
}

最新更新