简体   繁体   English

Java Apache POI防止数据在Excel中被覆盖

[英]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. 我正在从文件中读取json字符串,并对数据进行一些验证。 If any errors occur during validation, I write the data to an excel sheet. 如果在验证过程中发生任何错误,我会将数据写入Excel工作表。 My problem is my excel sheet is getting overwritten each time. 我的问题是我的Excel工作表每次都被覆盖。 As you can see in the writeErrorsToSpreadSheet method, I put that data in the sheet in the same row. 如您在writeErrorsToSpreadSheet方法中所看到的,我将该数据放在工作表的同一行中。 Every time the for loop is called in the writeErrorsToSpreadSheet method, count is getting set to 0, and the data is getting overwritten. 每次在writeErrorsToSpreadSheet方法中调用for循环时,count都将设置为0,并且数据将被覆盖。 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. 每次调用writeErrorsToSpreadSheet ,它将创建一个新的空白工作簿并创建一个工作表。 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对象。

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. 然后,您可以使用SheetgetLastRowNum方法在表单中找到最后一个填充的行,您可以使用该方法将数据添加到下一行。

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. 您可能还需要考虑在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