通过java apache POI在excel文件中追加新行

时间:2016-06-20 08:21:59

标签: java excel apache-poi

我有一个现有的xlsx文件,在第1行我有我的标题,我需要的是在2处添加新行,当然还要将其他所有内容向下移动,然后将我的数据添加到此行。你能帮帮我吗?

static void Append() throws EncryptedDocumentException, InvalidFormatException, IOException
{
    InputStream inp = new FileInputStream("C:/workbook.xlsx");

    Workbook wb = WorkbookFactory.create(inp);
    Sheet sheet = wb.getSheetAt(0);

    Row row = sheet.createRow((short) 2);
    sheet.shiftRows(1, sheet.getLastRowNum()+1, 1, true,true);
    row.createCell(0).setCellValue("A");
    row.createCell(1).setCellValue("B");
    row.createCell(2).setCellValue("This is a string");
    row.createCell(3).setCellValue(true);

    // Write the output to a file
    FileOutputStream fileOut = new FileOutputStream("C:/workbook.xlsx");
    wb.write(fileOut);
    fileOut.close();
}

1 个答案:

答案 0 :(得分:3)

确实方法shiftRows是满足这种需求的一个很好的选择,你只需要更好地设置参数,如下所示:

...
// Shift of one row all the rows starting from the 3th row
sheet.shiftRows(2, sheet.getLastRowNum(), 1, true, true);
// Create my new 3th row
Row row = sheet.createRow(2);
...