簡體   English   中英

Java Apache POI防止數據在Excel中被覆蓋

[英]Java Apache POI prevent data from getting overwritten in excel

我正在從文件中讀取json字符串,並對數據進行一些驗證。 如果在驗證過程中發生任何錯誤,我會將數據寫入Excel工作表。 我的問題是我的Excel工作表每次都被覆蓋。 如您在writeErrorsToSpreadSheet方法中所看到的,我將該數據放在工作表的同一行中。 每次在writeErrorsToSpreadSheet方法中調用for循環時,count都將設置為0,並且數據將被覆蓋。 我已經運行了調試器,並嘗試了多種方法來解決此問題,但無濟於事:(有人可以指導我如何在不覆蓋文件的情況下附加到文件嗎?

public static void main( String[] args ) throws Exception
    {
        File[] files = findFilesInDir("/home/input");
        if(files!=null && files.length!=0) {
            List<String> fileData = new ArrayList<String>();
            for(File file:files) {
                fileData.add(readFileContents(file.getAbsolutePath()));
                validateData(file); //this is where data validation happens. if anything fails here, i write the data to the spread sheet. the excel sheet is getting overwritten here
            }

    }

    public static String readFileContents(String location) throws IOException {
    InputStream is = new FileInputStream(location);
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();
    String line;
    while ((line = reader.readLine()) != null) {
        sb.append(line);
    }
    reader.close();
    return sb.toString();
}



Here is the validateData method - 

validateData(String file,Person person) {
//do some string validation, and write the error to a spread sheet
writeErrorsToSpreadSheet(person);   

}

In the test class, here is the writeToSpreadSheet method
private static void writeErrorsToSpreadSheet(Person person) throws IOException {
    HSSFWorkbook workbook = new HSSFWorkbook();
    HSSFSheet sheet = workbook.createSheet("Test Sheet");
    FileOutputStream fis = new FileOutputStream("input.xls");
    Map<String,Object[]> data = new LinkedHashMap<String,Object[]>();
    data.put("1", new Object[]{"Name","Address","PhoneNumber"});
    int count=0;
    for(Map.Entry<String, String> errorMp:errorMap.entrySet()) {
        data.put(Integer.toString(count+2), new Object[]{person.getName(),person.getAddress(),person.getPhoneNumber()});
        count++;
    }

    Set<String> keyset = data.keySet();
    int rownum = 0;
    for (String key : keyset) {
        Row row = sheet.createRow(rownum++);
        Object [] objArr = data.get(key);
        int cellnum = 0;
        for (Object obj : objArr) {
            Cell cell = row.createCell(cellnum++);
             if(obj instanceof String)
                cell.setCellValue((String)obj);
        }
    }
    workbook.write(fis);
    if(fis!=null)
        fis.close();
}

每次調用writeErrorsToSpreadSheet ,它將創建一個新的空白工作簿並創建一個工作表。 然后,將其寫入文件,覆蓋那里的舊文件。

如果要將此方法追加到現有工作簿中,則必須通過加載現有工作簿來創建HSSFWorkbook對象。

HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream("input.xls"));

然后,您可以使用SheetgetLastRowNum方法在表單中找到最后一個填充的行,您可以使用該方法將數據添加到下一行。

您可能還需要考慮在org.apache.poi.ss.usermodel包中使用“ HSSF”(。xls)和“ XSSF”(。xlsx)世界之間的通用接口,並且可以使用WorkbookFactory獲取一個新的Workbook ,將適用於.xls( HSSFWorkbook )和.xlsx( XSSFWorkbook )文件。

暫無
暫無

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

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