Apache POI将数据附加到Excel工作表不起作用

时间:2014-08-08 18:05:51

标签: java apache-poi

我正在阅读arraylist中的数据并将其写入excel表。问题是我的excel每次都被覆盖。这是我的代码。我无法弄清楚这里有什么问题:(有人可以帮忙吗?

public static void main( String[] args ) throws Exception
{
        List<String> fileData = new ArrayList<String>();
        for(File file:files) {
            fileData.add(readFileContents(file.getAbsolutePath()));
        }
        for(String fileContent:fileData) {
            //do some stuff that in turn calls the writeDataToExcel method 

    }
}

private static void writeDataToExcel(String test,Map<String,String> dataMap,Object object) throws IOException {
    File file = new File("input/data.xls");
    Map<String,Object[]> data = new LinkedHashMap<String,Object[]>();       
    XSSFWorkbook workbook = null; 
    int count = 0;
    XSSFSheet sheet = null;
    if(file.exists()) {
        workbook = new XSSFWorkbook(new FileInputStream(file));
        sheet = workbook.getSheet("Data Sheet");
    }
    else {
        workbook = new XSSFWorkbook();
        sheet = workbook.createSheet("Data Sheet");
        //count = sheet.getLastRowNum();
    }

    data.put("1", new Object[]{"Id","Name","Field","Description","Value"});
    for(Map.Entry<String, String> dataMp:dataMap.entrySet()) {
        data.put(Integer.toString(count+2), new Object[]{id,object.getClass().getSimpleName(),dataMp.getKey(),dataMp.getValue(),"null"});
        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);
        }
    }
    FileOutputStream fis = new FileOutputStream("input/data.xls");
    workbook.write(fis);
    if(fis!=null)
        fis.close();
}

1 个答案:

答案 0 :(得分:1)

我认为问题在线

int rownum = 0;

每次将rowNUm设置为零,并且将从零行写入工作表

如果要在表格中附加数据,则需要保留此rowNum