通过Java Apache POI向Excel文件追加新行

4

我有一个现有的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个回答

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);
...

主线程异常:"main" java.lang.IllegalArgumentException: firstMovedIndex,lastMovedIndex顺序错误 在org.apache.poi.ss.formula.FormulaShifter.<init>(FormulaShifter.java:81)处 在org.apache.poi.ss.formula.FormulaShifter.createForRowShift(FormulaShifter.java:126)处创建 在org.apache.poi.xssf.usermodel.XSSFSheet.shiftRows(XSSFSheet.java:2970)处移动行 在MainClass.Append(MainClass.java:67)处添加 在MainClass.main(MainClass.java:21)处 - Dim
这适用于一个简单的 xlsx 文件,也许您应该提供更多关于您的文件的信息。 - Nicolas Filotto
1
你还应该在问题中清楚地提到遇到的问题。 - Nicolas Filotto
sheet.shiftRows(1, sheet.getLastRowNum(), 1, true,true); Row row = sheet.createRow(1); - Dim

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接