简体   繁体   中英

Java Apache POI prevent data from getting overwritten in excel

I am reading json strings from a file, and I do some validation on the data. If any errors occur during validation, I write the data to an excel sheet. My problem is my excel sheet is getting overwritten each time. As you can see in the writeErrorsToSpreadSheet method, I put that data in the sheet in the same row. Every time the for loop is called in the writeErrorsToSpreadSheet method, count is getting set to 0, and the data is getting overwritten. I have ran the debugger, and tried multiple ways to fix this, but to no avail :( Can someone please guide me how do I append to the file without overwriting it?

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();
}

Every time writeErrorsToSpreadSheet is called, it creates a new, blank workbook and creates a sheet. Then you write it to the file, overwriting the old file that was there.

If you want this method to append to an existing workbook, then you must create the HSSFWorkbook object by loading the existing workbook.

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

Then you can find the last populated row in the sheet with Sheet 's getLastRowNum method, which you can use to add data to the next row.

You may also want to consider using the common interface between the "HSSF" (.xls) and "XSSF" (.xlsx) world, in the org.apache.poi.ss.usermodel package, and you can use WorkbookFactory to get a new Workbook , which will work for .xls ( HSSFWorkbook ) and .xlsx ( XSSFWorkbook ) files.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM