为什么在复制Excel内容时仅设置了最后一个值?

时间:2019-06-13 08:47:20

标签: java xssf

我正在尝试将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 |

有人知道吗?非常感谢!

1 个答案:

答案 0 :(得分:0)

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)

        }
}