簡體   English   中英

使用Poi附加數據而不會覆蓋標題

[英]Append data with Poi without overwriting headers

我有下面的代碼,我要將數據附加到.xlsx文件中,但是新的輸入僅覆蓋了我在現有文件中已經擁有的標題行。 我知道XSSFRow存在問題,因為我不知道如何定義新輸入的寫入位置。

有人可以指導我或幫助我確定如何解決此問題嗎? 這將不勝感激。

親切的問候,

尼科斯。

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())的下一個調用將完全按照您的描述進行操作:在標題行的位置創建一個NEW行,並用新數據覆蓋它。

您已經知道如何使用sheet.createRow();。 因此,只需從索引1開始創建行並將數據寫入其中。 行號0是標題行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM