用Poi追加数据而不覆盖标题

我有下面的代码,我想要在.xlsx文件中追加数据,但新的input只是写在我已经在现有的文件中的标题行。 我知道XSSFRow存在一个问题,因为我不知道如何定义我希望写入新input的位置。

有人可以指导我或帮助我确定如何解决这个问题? 这将不胜感激。

亲切的问候,

尼科斯。

public static String path = "File Path"; public static String excelFile = "workbook.xlsx"; public static XSSFWorkbook myWorkBook; public static XSSFSheet mySheet; public static XSSFRow myRow; public static void appendValues() throws Exception { System.out.println("Appending values"); File testFile = new File(path + excelFile); FileInputStream fis = new FileInputStream(testFile); // Finds the workbook instance for XLSX file myWorkBook = new XSSFWorkbook(fis); // Return first sheet from the XLSX workbook mySheet = myWorkBook.getSheetAt(0); myRow = mySheet.createRow(mySheet.getLastRowNum()); System.out.println("Row: " + (myRow)); Map<String,String> appendData=new HashMap<>(); appendData.put("Defect Reference", "Defect ref"); appendData.put("Defect ID", "ID"); appendData.put("Fielda", "field"); String[] headerArray = getHeaders().toArray(new String[0]); for(int i=0;i<headerArray.length;i++) { String val=appendData.get(headerArray[i]); if(val!=null) { Cell cell = myRow.createCell(i); cell.setCellType(Cell.CELL_TYPE_STRING); cell.setCellValue(val); System.out.println("insert Value: " + val); } else { Cell cell = myRow.createCell(i); cell.setCellType(Cell.CELL_TYPE_STRING); cell.setCellValue(""); } } FileOutputStream fos = new FileOutputStream(path + excelFile); myWorkBook.write(fos); fos.close(); } 

调用mySheet.getLastRowNum()将返回表单最后一行的索引。 在你的情况下从只有头文件的现有Excel文件读取的是头标行本身。

因此,对mySheet.createRow(mySheet.getLastRowNum())的下一次调用将mySheet.createRow(mySheet.getLastRowNum())您所描述的操作:在标题行的位置创build一个新行,并用新数据覆盖它。

你已经知道如何使用sheet.createRow(); 所以只需从索引1开始创build行并向其写入数据即可。 行号0是标题行。